Disclaimer: This challenge is extremely scientifically inaccurate. ;)
Given an input of a list of molecules, output what the result would be if they were to all combine via dehydration synthesis, if possible.
For the purposes of this challenge, although this description is inaccurate, a dehydration reaction between two molecules is performed as follows:
OH(one oxygen and one hydrogen atom) from either of the two molecules.
H(a single hydrogen atom) from the other one.
Combine the two molecules into one.
For instance, combining two
C6H12O6 molecules via dehydration
synthesis would result in
C12H22O11. Note that there are
Hs and one less
O in the product than in the reactants. (These
missing parts would form
H2O, hence "dehydration," but
that's irrelevant to this challenge.)
An example of molecules that cannot be combined via dehydration synthesis is
CO2. The required amount of hydrogen and oxygen is
present, but neither
H can be taken from the
The format of the input for each molecule is a list of atoms concatenated. An
atom is always a single capital letter, possibly followed by a single lowercase
letter (you don't have to handle atoms like
Uuo). Atoms may also have
integers ≥ 2 after them, representing how many of them there are; if this
number is not present, it is assumed to be 1. Atoms will never be repeated
within the same molecule.
Input may be provided as either an array/list/etc. of strings, or a single string separated by any non-alphanumeric character. Output must be a single string, but the output for "invalid input" (i.e. a list of molecules that cannot be combined via dehydration synthesis) may be any string containing at least one non-alphanumeric character (to distinguish from valid output). The order of the atoms in the output does not matter.
Since this is code-golf, the shortest code in bytes will win.
Test cases (invalid output is represented here by an asterisk
In Out ------------------------------------------------------------------ C6H12O6 C6H12O6 C6H12O6 C6H12O6 C6H12O6 C6H12O6 | C36H62O31 CHO5 CH2 CH2 CH2 CH2 CH2 | C6H CHO4 CH2 CH2 CH2 CH2 CH2 | * H H H CH3O3 | C H H H CH4O2 | * C6H12O6 ABCDELMNOP C6H12O6 | * HO HO HO H3 | <empty string> HgO4 C6H12O6 | * HgHO4 C6H12O6 | HgH11O9C6 PdZnXeRaHO KrArKRbFH | PdZnXeRaKrArKRbF