I'm trying to make a system to factorise (if that term is correct in Chemistry) a given expanded chemical formula, such as C6H2NO2NO2NO2CH3
into brackets so that it is C₆H₂(NO₂)₃CH₃
. (Ignore the subscript, or lack thereof in the first instance). Problem is, I don't know what the repeated molecule is going to be, or even how long it will be. How would I find and count repeats?
For context, here's my code so far which generates the formula from a 2D list of elements:
private String getFormula(List<List<Element>> elements)
{
String formula = ""; //TODO Switch out for StringBuilder
for(List<Element> currentElement : elements)
{
formula += currentElement.get(0).getSymbol(); //Every element per list is identical, so looking at 0 will always be safe
if(currentElement.size() > 1) formula += currentElement.size(); //Only display a number if there is more than 1 element
}
return formula;
}
>? Where is the definition of Element -- does it have a .equals() method for example? And it has been a while, but NO2 isn't an element, it's compound, non? In essence, I would probably create a TreeMap (or LinkedHashMap) to preserve order, traverse the entire input, and then traverse the Map adding parenthesis and count around the element if the value was > 1.
– KevinO Mar 29 '16 at 19:40