In this challenge, your task is to take an anion and a cation, and output the chemical formula of the compound.
Input rules
- Take in 2 strings (in any order) representing the anion and cation, e.g.
F
,NH_4
, orAl
. - To take in the charge of each ion, you can either have it as part of the string separated by a caret (e.g.
F^-1
) or take in additional numerical arguments. - Note: As long as your numeric input type is signed, then the anion's charge will be passed in as a negative number.
- The symbols will always be real, and charges accurate.
Output rules
- Use
_
for subscripts: Fe2O3 would beFe_2O_3
. - Cation first: NaCl, not ClNa.
- Neutral molecule: Li2O, not LiO or LiO-.
- Lowest possible coefficients: Fe2O3, not Fe4O6.
- No subscript ones: NaCl, not Na1Cl1.
- No shifting: NH4OH, not NH5O.
- Conditional parentheses:
- Do not use parentheses on a single-atom ion: MgCl2, not Mg(Cl)2.
- Do not use parentheses if there is only one of the ion per molecule: KClO3, not K(ClO3).
- DO use parentheses if there are two or more of a polyatomic ion: Be3(PO4)2, not Be3PO42 or Be3P2O8.
Testcases
Input Output
Fe^+3, O^-2 Fe_2O_3
Fe^+2, O^-2 FeO
H^+1, SO_4^-2 H_2SO_4
Al^+3, SO_4^-2 Al_2(SO_4)_3
NH_4^+1, SO_4^-2 (NH_4)_2SO_4
Hg_2^+2, PO_4^-3 (Hg_2)_3(PO_4)_2
NH_4^+1, OH^-1 NH_4OH
Hg_2^+2, O_2^-2 Hg_2O_2
This is code-golf, the shortest answer in bytes wins!
Fe^+2, OH^-1: Fe(OH)_2
for a polyatomic ion with 1 of each element (OH^-1
). \$\endgroup\$NO_3^-1
. Also another test case should be the first one paired up with a^-2
, so it would make(C(NH_2)_3)_2...
. Or a case where the ion that is needed more than once begins with a bracket. \$\endgroup\$Fe_4(Fe(CN)_6)_3
for Prussian blue. \$\endgroup\$