0

I am making a java application that balances chemical equations. I loop through each term and create two arraylists. In one arraylist, I have the set of all of the elements. For example (in the first term) if the equation is C6H12O6+O2=CO2+H2O, the arraylist will have {C, H, O}. In another, I have the corresponding numbers, so it will contain {6,12,6}. I need to combine all of these to form a matrix (3 by 4), which would be:

(0,0) = 6 (1,0) = 12 (2,0) = 6 (0,1) = 0 (1,1) = 0 (2,1) = 2 (0,2) = 1 (1,2) = 0 (2,2) = 2 (0,3) = 0 (1,3) = 2 (2,3) = 1

The matrix above is designed so that row 0 is C, row 1 is H, and row 2 is O. The columns are the terms (0, 1, 2, and 3)

Any suggestions for converting the arraylists into a matrix?

Upas
  • 1
  • Umm. I'm pretty sure you lose information the way you're doing it. And that's not a matrix. What about something like (2,3). What does that represent? – Falmarri Dec 29 '10 at 22:49

3 Answers3

3

If you are doing this for fun or a project, fine. If you are doing this for a real extensible application to be used by chemists then you will need to cater for > 100 elements, many reagents and products and fractional amounts. There are a lot of Open Source Java chemistry libraries and I'd be happy to introduce you. Do not re-invent the wheel. See http://www.blueobelisk.org

To do this seriously requires a Bond/Electron matrix as developed by Ugi. Your best place is Ugi's own paper: www.iupac.org/publications/pac/1978/pdf/5011x1303.pdf

see - e.g. p 1307.

EDIT: This is overkill for the current problem!

A simple matrix approach would include 2 coupled matrices R (reactants) and P (products) with nelem (say 100) columns for known elements and an indefinite number of rows (nR, nP) as many reactants and products. The matrices would therefore generally not be of equal dimensions. reactant[nR][nelem] and product [nP][nelem]. There would also be two column vectors for the multipliers nreact[nR] and nprod[nP]. Note that in general chemical formulae and multipliers are commonly integral but need not be (may compounds do not have simple integer ratios of elements).

I would use my own CMLFormula and CMLReaction Java classed (see http://www.xml-cml.org) to tackle this. You are welcome to start there - it will make life easier

peter.murray.rust
  • 37,407
  • 44
  • 153
  • 217
0

You can represent a matrix by arrays: think of each row as an array of column data:

[[6 12 6], 
 [0 0  2], 
 [1 0  2], 
 [0 2  1]]

This way, your matrix point is a reference to the array position inside another array at a given point. in other words:

matrix[0][2] == 2

(for the first array (0), second position (1))

I can't speak for or against your logic in the chemistry, though. :)

ballpointcarrot
  • 113
  • 1
  • 6
0

If you want good matrix operations in java look at JAMA (Java Matrix)

Pradeep Gollakota
  • 2,161
  • 16
  • 24