parse number of atoms in a molecule | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

parse number of atoms in a molecule

i come up with this solution but it works only with single letter molecules. pls help me with changes required for molecules with 2 character like Na2Cl3OH https://code.sololearn.com/c04N5cq6IDdo/?ref=app

26th May 2018, 3:36 PM
Pavan M
Pavan M - avatar
4 Answers
+ 5
A complete sample: import java.util.regex.*; import java.util.*; class Dcoder { public static void main(String s[]) { String input = "Na2Cl3OH"; Pattern p = Pattern.compile("(Na|Cl|O|H)([0-9]*)"); Matcher m = p.matcher(input); Map <String, Integer> atoms = new HashMap<>(); while (m.find()) { String element = m.group(1); Integer count = Integer.parseInt(m.group(2).equals("") ? "1" : m.group(2)); atoms.put(element, count + (atoms.get(element) == null ? 0 : atoms.get(element))); } System.out.println(atoms); } }
26th May 2018, 6:11 PM
Hatsy Rei
Hatsy Rei - avatar
+ 5
In order for it to properly recognise elements in the molecule, you have to teach it about element symbols. This can be easily achieved by altering the regex pattern. Pattern p = Pattern.compile("([A-Z])([0-9]*)"); The current regex pattern recognises any single character [A-Z] followed by 0 or more numeric values. Do something like: Pattern p = Pattern.compile("(Na|Cl|O|H)([0-9]*)"); in order to get it to capture the element symbols properly. However, you still have to fix the part about printing the element names. Your current implementation prints only the first character from the first captured group using regex. Try to alter the program to print two characters when required.
26th May 2018, 5:58 PM
Hatsy Rei
Hatsy Rei - avatar
+ 5
Where did you get this code by the way... It blew my previous attempt to help you off into space so I'm quite salty at the moment.
26th May 2018, 6:04 PM
Hatsy Rei
Hatsy Rei - avatar
0
thank you
26th May 2018, 6:12 PM
Pavan M
Pavan M - avatar