ashley smith
ashley smith

Reputation: 43

How would I Evaluate a certain formula?

I have a multidimension arrayList and I ask the user for a formula and than I evaluate it. The problem is that I get user input like this:

  ((a1+a2)/12)*a3

the problem is that a1 and a2 and a3 refer to columns and I have to evaluate it to a certain value to it and I am totally lost on how to approach this problem any advice or guidance would be great. Also this calculate value has to update every time the value in any of the columns Update. The thing is the formula isn't hard coded.

Upvotes: 0

Views: 186

Answers (4)

fruchtose
fruchtose

Reputation: 1320

An alternative to Heisenbug's suggestion is to try Dijkstra's shunting-yard algorithm. Instead of relying on a tree structure, you use stacks and queues. The advantage is that these data structures involved are not terribly complicated. The downside is that any errors in implementing the algorithm could be easily missed, as you need to thoroughly understand the operations involved to know if your implementation is correct.

Upvotes: 1

Heisenbug
Heisenbug

Reputation: 39164

A possibility is write a sort of parser. It's better to use a binary tree structure to represent an expression, rather than a list.

Each non-leaf node is an operation and every leaf is operand.

tree

Upvotes: 3

Dave Newton
Dave Newton

Reputation: 160181

Personally, I'd try really hard to avoid all the parsing stuff, and look for an EL library that allows you to use your own variable resolver. All you'd need to do then is hook up the variables to your backing model. (In your case, splitting on word/letter boundary, and looking up cell contents.)

This would also allow you to include arbitrary functions by simply exposing them to the EL engine. Something like OGNL, MVEL, etc. might be a good starting point. Seems much easier.

Upvotes: 3

James
James

Reputation: 9278

You will need to turn the formula into something like a Binary Expression Tree. This should be not that difficult.

Then you will need to traverse this tree to evaluate the expression value at the start and each time a value in the arrayList changes. Concentrate first on building the tree and getting correct values when you evaluate it. Don't forget negative numbers and variables! Watching the arrayList for changes should be trivial after that.

Upvotes: 0

Related Questions