Chemistry Equation Balancer
Хімія
Statement
Write a program chemie.* that finds the smallest natural-number coefficients
(each no greater than 30) to place in front of every chemical formula in a
reaction so that the equation balances — the number of atoms of every element
is the same on both sides — and then writes out the correctly balanced
equation.
Input / Output
File chemie.dat contains the formulas of the reaction's reactants,
separated by + and written to the left of =, and of its products,
separated by + and written to the right of =. There are at most 10
substances in total. Every chemical element symbol (row 1 of the file) starts
with an uppercase Latin letter; an atom count greater than 1 is written below
and to the right of the symbol (row 2). A symbol may appear more than once in
one formula, and a parenthesized group may carry its own repeated-atom-count
subscript. File chemie.res reproduces the input with any coefficient other
than 1 inserted before the corresponding formula in row 1, and the matching
number of blank positions added to row 2 beneath that coefficient.
Constraints
- at most 10 substances (reactants + products) in total
- coefficients are natural numbers not exceeding 30
- the input guarantees a solution exists and is unique
Example
Input: Ba(OH)2 +HCl=BaCl2 +H2O
Output: Ba(OH)2 +2HCl=BaCl2 +2H2O
Solution idea
Parse each formula into a multiset of {element: atom count}. Balancing then
becomes an integer linear system: for every element, the sum of
coefficient × count over the reactants must equal the same sum over the
products. Because there are at most 10 species and coefficients are capped at
30, the small search space lets a direct search (or solving the stoichiometric
matrix's integer null space and scaling to the smallest positive integer
vector) find the unique balancing coefficients.