r/dailyprogrammer • u/jnazario 2 0 • May 31 '17
[2017-05-31] Challenge #317 [Intermediate] Counting Elements
Description
Chemical formulas describe which elements and how many atoms comprise a molecule. Probably the most well known chemical formula, H2O, tells us that there are 2 H atoms and one O atom in a molecule of water (Normally numbers are subscripted but reddit doesnt allow for that). More complicated chemical formulas can include brackets that indicate that there are multiple copies of the molecule within the brackets attached to the main one. For example, Iron (III) Sulfate's formula is Fe2(SO4)3 this means that there are 2 Fe, 3 S, and 12 O atoms since the formula inside the brackets is multiplied by 3.
All atomic symbols (e.g. Na or I) must be either one or two letters long. The first letter is always capitalized and the second letter is always lowercase. This can make things a bit more complicated if you got two different elements that have the same first letter like C and Cl.
Your job will be to write a program that takes a chemical formula as an input and outputs the number of each element's atoms.
Input Description
The input will be a chemical formula:
C6H12O6Output Description
The output will be the number of atoms of each element in the molecule. You can print the output in any format you want. You can use the example format below:
C: 6
H: 12
O: 6Challenge Input
CCl2F2
NaHCO3
C4H8(OH)2
PbCl(NH3)2(COOH)2Credit
This challenge was suggested by user /u/quakcduck, many thanks. If you have a challenge idea, please share it using the /r/dailyprogrammer_ideas forum and there's a good chance we'll use it.
3
u/KeinBaum May 31 '17
Are nested brackets supposed to be supported? I.e. something like
V(W(XY)2)3?8
u/skeeto -9 8 May 31 '17
C. It converts the atomic symbol into a table index, allowing the counts to be stored in a simple, flat table. Bracketed elements are read recursively.
4
u/Godspiral 3 3 May 31 '17 edited Jun 01 '17
in J, doesn't do brackets
with parens,
4
u/Jean-Alphonse 1 0 Jun 04 '17
Python: regex + recursion
1
u/Soccer21x May 31 '17
For the last challenge input, what would the '(COOH)2' come out to be? Was one of the Os supposed to be lower case? Or does that come out as C:2, O:4, H:2?
3
u/CrazyMerlyn May 31 '17
Solution in python
3
u/Scroph 0 0 May 31 '17 edited May 31 '17
Edit : fixed edge case where the formula ends with a molecule (as opposed to a number) and a few other bugs. No need to recompile because the output remains the same in this case.
+/u/CompileBot C++
Input:
3
u/mrploszaj May 31 '17
Solution in D. It basically uses a bunch of regex. Like, tons of regex.
2
u/pastrygeist May 31 '17
Python 3 +/u/CompileBot Python
Input
2
u/Zdup Jun 01 '17 edited Jun 01 '17
C++ Solution is straight forward, broken down as follows:
Results are gathered in a dictionary (map) and printed out.
2
u/FickleWalrus Jun 03 '17
Java solution. Fairly painless. Handles nested parens using a stack.
2
u/muskatnus Jun 10 '17 edited Jun 10 '17
Python solution with support for nested parentheses
1
u/KeinBaum May 31 '17
Scala
Parses input in linear time. Supports nested bracktes.
1
u/leSpectre May 31 '17 edited May 31 '17
OOP Python3 +/u/CompileBot Python 3
Input:
1
u/popillol May 31 '17
Go / Golang Playground Link. Does not support nested parens (but can do all challenge inputs)
Code:
1
u/LiveOnTheSun May 31 '17
C#, also handles nested brackets.
Output:
1
u/benz05 May 31 '17 edited May 31 '17
Python 3 Doesn't handle nesting of parenthesis, but I don't think this is applicable in this case.
1
u/Haversoe May 31 '17 edited Jun 01 '17
Once through the string with a recursive descent parser (no regexs). Nested parens supported but no error checking:
Python 3 +/u/CompileBot Python
Input:
1
u/longlivesquare May 31 '17
Go
Doesn't handle nested parentheses
1
u/krismaz 0 1 May 31 '17
In Pyth, we are going to cheat ever so slightly.
Parsing parenthesized strings, while keeping a constant counts, seems slightly complicated, so instead, let's rewrite the input string into a Python expression that builds the list of atoms for us.
Finally, the matter of counting the number of each atom is fairly simple, giving a solution looking like this:
Unfortunately, this will not work in the online interpreter, since it is grossly insecure.
I'm still very new at Pyth, so I'm fairly certain that there might be a shorter, or at least more elegant solution out there.
1
u/macsilvr Jun 01 '17
Solution in Python with a fancy named regex tokenizer and recursive descent parser. Works with nested parenthesis, but they must have a postfixed number (i.e. no extraneous parentheses are allowed).
Output:
1
u/LenAnderson Jun 01 '17 edited Jun 01 '17
Groovy
+/u/CompileBot Groovy
Input:
1
u/conceptuality Jun 01 '17
Python 3:
Splits the words by parenthesis and uses the number outside as a multiplier. Then it groups them by uppercase letters.
This won't work for nested parentheses.
code:
1
u/hyrulia Jun 02 '17 edited Jun 02 '17
Kotlin
1
u/guatsf Jun 02 '17
R
This kept me up until 5:37 am. No ragrets though. Any comment, opinion or anyway you think I can make this better (I am sure there are plenty) are much appreciated.
+/u/CompileBot R
1
u/mochancrimthann Jun 02 '17 edited Jun 02 '17
JavaScript ES6
1
u/[deleted] Jun 02 '17 edited Jun 02 '17
Common Lisp
Not a short solution by any stretch of the imagination, rather a "general" one (can also parse nested brackets) using continuation-passing-style to implement the parser. The parser is quite general and can deal with ambiguity. Note that the parsing part is a little bit uglier than it needs to be, as I wanted to have the parsing tree have a nice structure.
Comments appreciated.
+/u/CompileBot Lisp
1
u/den510 Jun 02 '17
Ruby
This is a relatively short solution, no nested bracket parsing included. I realize that's what would make this tool very useful, however, and will continue to chug away in my free time. My unique-ish twist: Element names from the symbols (awwwwww yeah).
edit formatting
+/u/CompileBot Ruby
1
u/IKLeX Jun 02 '17
Python 2.7.8
It even got recursion. Took me longer than I wanted, but on the other hand, I never used classes in python before (well I had to because I didn't want to alter a global variable and tehre is no call by reference)
Gimme a Molecule: CCl2F2
{'C': 1, 'F': 2, 'Cl': 2
Gimme a Molecule: NaHCO3
{'Na': 1, 'C': 1, 'O': 3, 'H': 1}
Gimme a Molecule: C4H8(OH)2
{'H': 10, 'C': 4, 'O': 2}
Gimme a Molecule: PbCl(NH3)2(COOH)2
{'C': 2, 'Cl': 1, 'H': 8, 'O': 4, 'N': 2, 'Pb': 1}
Bonus:
Gimme a Molecule: (C3(H2O)3)2
{'H': 12, 'C': 6, 'O': 6}
1
u/Executable_ Jun 02 '17
Python3
1
u/dancinggrass Jun 02 '17 edited Jun 02 '17
Nim solution.
Should handle any kind of nested proper parentheses and any number. The code is long because I tried to use as many language feature
1
u/itachi_2017 Jun 03 '17
Python New here.. Need feedback on my approach and code style. It first finds out all the elements in the molecule and instantiates class with a dictionary with counts of all molecules set to 0. Now when parse function gets called, it loops over all the elements and finds the number next to the elements. If "(" is encountered, a new base dict with all values of involved elements as zero is appended to answ list. when ")" is encountered it simply counts the number next to it and multiplies last dictionary in the list and adds the counts to second last dict. and pops the last dict from the list.
1
u/Sturnclaw Jun 03 '17
Lua 5.3.3. Theoretically infinite recursion, only bounded by stack size. Will error on incorrect formatting.
EDIT: Apparently reddit doesn't like triple grave code blocks.
1
u/Fushoo Jun 03 '17
Kotlin
Really enjoyed this challenge
Output:
1
u/haukuri Jun 04 '17
Python 3. The parsing part is implemented using the excellent Parsimonious library.
1
u/J_Gamer Jun 04 '17
C++
This was pretty fun to do, the two functions in the detail namespace are there to make adding elements possible when merging sets of the recursive parsing.
1
u/[deleted] Jun 05 '17
PASCAL First year in computer science and exam tomorrow :)
1
u/Specter_Terrasbane Jun 06 '17
Python 2
Stack-based, handles nested parens with or without trailing subscripts.
+/u/CompileBot Python
1
u/matt_the_rapper Jun 06 '17
Javascript in 32 lines
1
u/YallOfTheRaptor Jun 08 '17
Python 3
I've been trying to learn how to program for the last year or so and I feel like I've made decent progress, but I feel like I've been stuck in some sort of limbo between absolute beginner and programmer. This is my first submission and I'm looking forward to building up some experience and changing how I think about problems. This was very challenging for me, but it really helped me stretch. I knew I could use regular expressions, but sheesh I was not making any sense of the pattern stuff until tonight. I definitely did not have to re-write this completely after not paying attention to the challenge inputs. I am looking forward to any feedback!
1
u/magicbicycle Jun 08 '17
Python3:
Output:
1
u/A-Grey-World Jun 08 '17
Javascript. Probably not the most efficient method. It goes over recursively subdivides the bracketed sections, so it will pass over multiple times. There's probably a clever way of doing it in one pass.
I also split it into two distinct functions, as I found this easier conseptually. It'll probably be possible to just do the element counting, and bracket subdivision in a single function rather than first creating sub-sections, then passing them on for counting.
Link:
https://repl.it/IcMw/2
Code:
1
u/IPV4clone Jun 08 '17
C#
Code:
Input/Output:
1
u/e163026 Jun 09 '17
Solution in Python 2, feedback would be appreciated:
1
u/hindmost-one Jun 12 '17
Prolog. It parses formula via DCG and then it sums all the chemical elements. https://gist.github.com/Heimdell/6fd04ccad92e51f602ad03b53451ba4b
1
u/jthom179 Jun 14 '17
This program solves the problem in ruby. It is somewhat lengthy, so I have posted it here
1
u/zatoichi49 Jun 20 '17 edited Jun 20 '17
Method:
Use regex to parse the individual elements, along with their index position within the formula. Take each left parentheses in turn and set a counter to 1. Moving right from that position, counter+1 if you find another left parentheses, and counter-1 if you find a right parentheses. When counter=0, you'll have found the matching pair (the multiplier follows immediately after the right parentheses). For each of the elements, if the index of the elements falls within the index of the parentheses group, apply the multiplier to each element. Then add each (element, element count) pair into a dictionary and sum any duplicates. Also works for nested parentheses.
Python 3:
Output:
1
u/mistahchris Jun 28 '17
Python solution.
1
u/KinOfMany Jun 30 '17
I've seen plenty of Python implementations with regex, so I made one without regex for the hell of it. Just a single recursive function. Let me know if it could be optimized, I'm sure it could be and any input is welcome :)
1
u/Riverdan4 Jul 05 '17
Python 3 using recursion:
1
u/SirThomasTheBrave Jul 09 '17
Ruby Doesn't support nested elements. Any critique/feedback is welcome.
1
u/dodheim Aug 07 '17 edited Aug 19 '17
Late entry for C++17 + Boost.Spirit.X3 (supports arbitrarily-nested brackets):
Full code: https://gist.github.com/dodheim/7e7bf7b43d7dfcc48adad39db932660b
Online demo w/ output: https://wandbox.org/permlink/9EG412v4BktHmcXS
1
u/dodheim Aug 25 '17
Late entry for Rust + nom (supports arbitrarily-nested brackets):
Full code: https://gist.github.com/dodheim/706f5a10be507787514cbd1fbc724648
Online demo w/ output: https://play.rust-lang.org/?gist=783ea213aa47a7a0d09da0f40310945d&version=nightly
1
u/ironboy_ Oct 14 '17
JavaScript - short and regexpy
Output
1
u/svgwrk May 31 '17 edited May 31 '17
Rust solution. I guess practically all of the work takes place in that one method. I feel a little dirty about that. But. Yeah. Whatever. The worst part was making the flatmap -> map thing work; had to find the right place to add a
move. Stupid closures.1
u/cosm_rc1 May 31 '17 edited May 31 '17
Rust Rust really needs HashMap macro.
0
u/[deleted] Jun 10 '17
[deleted] — view deleted comment
1
u/[deleted] Jun 02 '17 edited Jun 02 '17
[removed] — view removed comment