Hi guys. First of all, I am aware that there is a somewhat similar thread over here. However, it was never really answered and the code given was obscure (I don't like copying stuff anyway)

Either way... I want to balance a chemical equation. However, I don't need help on parsing a string or anything (which is what most other search results on Google turn up), because the compounds on either side are already separated into their constituent elements, as this is not a standalone app but part of a larger project I'm working on.

I also know that I can balance a chemical equation mathematically using matrices and a set of simultaneous equaations (And I plan to do so using the Apache Commons Math Library).

My problem, then, is how to put transform a bunch of elements on two sides to a bunch of solvable equations representable in matrix form... Programatically.

Thanks for all the help!

Start by counting the number of substances involved, including both reactants and products. That will be the number of columns of your matrix. Since your equation is already parsed, I expect that number is easily obtained.

Next you create a list of the elements involved. For example if H2O is a product then that would mean H and O would need to be in your list, but only include each element once. You wouldn't want two Hs. You can do that by iterating through your formula and filling a java.util.Set with the elements you find, then constructing a new java.util.ArrayList(elementSet). The length of your list is the number of rows in your matrix, so now you can construct your matrix and you are ready to fill it.

Go one row at a time. For row i, get element i from your element list and then iterate through your formula checking how many atoms of each element are in each substance. Put the number of atoms for the first substance in the first column, and so on for each reactant. When you get to the products you will do the same thing except make the numbers negative.

Then you should have your matrix, and your element list tells you what each row represents.

This article has been dead for over six months. Start a new discussion instead.