12
2
Challenge
Given the formula of a chemical, output the Mr of the compound.
Equation
Each element in the compound is followed by a number that denotes the number of said atom in the compound. If there isn't a number, there is only one of that atom in the compound.
Some examples are:
- Ethanol (C2H6O) would be
C2H6O
where there are two carbon atoms, 6 hydrogen atoms and 1 oxygen atom - Magnesium Hydroxide (MgO2H2) would be
MgO2H2
where there is one magnesium atom, two oxygen atoms and two hydrogen atoms.
Note that you will never have to handle brackets and each element is included only once in the formula.
Whilst most people will probably stick to the order they feel most comfortable with, there is no strict ordering system. For example, water may be given as either H2O
or OH2
.
Mr
Note: Here, assume formula mass is the same as molecular mass
The Mr of a compound, the molecular mass, is the sum of the atomic weights of the atoms in the molecule.
The only elements and their atomic weights to 1 decimal place that you have to support (hydrogen to calcium, not including noble gases) are as follows. They can also be found here
H - 1.0 Li - 6.9 Be - 9.0
B - 10.8 C - 12.0 N - 14.0
O - 16.0 F - 19.0 Na - 23.0
Mg - 24.3 Al - 27.0 Si - 28.1
P - 31.0 S - 32.1 Cl - 35.5
K - 39.1 Ca - 40.1
You should always give the output to one decimal place.
For example, ethanol (C2H6O
) has an Mr of 46.0
as it is the sum of the atomic weights of the elements in it:
12.0 + 12.0 + 1.0 + 1.0 + 1.0 + 1.0 + 1.0 + 1.0 + 16.0
(2*C + 6*H + 1*O)
Input
A single string in the above format. You can guarantee that the elements included in the equation will be actual elemental symbols.
The given compound isn't guaranteed to exist in reality.
Output
The total Mr of the compound, to 1 decimal place.
Rules
Builtins which access element or chemical data are disallowed (sorry Mathematica)
Examples
Input > Output
CaCO3 > 100.1
H2SO4 > 98.1
SF6 > 146.1
C100H202O53 > 2250.0
Winning
Shortest code in bytes wins.
This post was adopted with permission from caird coinheringaahing. (Post now deleted)
Do we have to handle quantifiers, such as:
2H2O
? – Mr. Xcoder – 2017-06-11T12:21:49.4706For the curious, this is the Mathematica solution (53 bytes):
NumberForm[#&@@#~ChemicalData~"MolecularMass",{9,1}]&
– JungHwan Min – 2017-06-11T13:59:25.983