|
-
Apr 27th, 2006, 02:22 PM
#10
Frenzied Member
Re: Back to math
It's probably not the best way, but if I was going to do it, I'd create an object that represents an expression, and attach an ArrayList or a linked list to it or something that represented each part of the expression as the same type of object, and so on until the expression was broken down to the lowest elements, and I'd sort the list by order of operations. Then when I was evaluating the expression, I'd start of with the first child object, and follow the children all the way down to the lowest level, do all those operations, then float up to the next level, 2nd object, and follow the tree down again.
So: 4 + (5 * 7) / 3
MasterObject.Expression = "4 + (5 * 7) / 3"
MasterObject.SubExpressions(0) = (5 * 7)
MasterObject.SubExpressions(1) = MasterObject.SubExpressions(0) / 3
MasterObject.SubExpressions(2) = MasterObject.SubExpressions(0) + 4
Or a More complex:
10 * (7 + 4 / 2) - 13
MasterObject.Expression = "10 * (7 + 4 / 2) - 13"
MasterObject.SubExpressions(0) = (7 + 4 / 2)
MasterObject.SubExpressions(0).SubExpressions(0) = 4 / 2
MasterObject.SubExpressions(0).SubExpressions(1) = MasterObject.SubExpressions(0).SubExpressions(0) + 7
MasterObject.SubExpressions(0) = MasterObject.SubExpressions(1) * 10
MasterObject.SubExpressions(0) = MasterObject.SubExpressions(2) - 13
So basically you just order your children by mathimatical order of operation, and then run down the tree. So we start at child Object 0.
Object 0 - > Have children? Yes, Go down one
Object 0, Object 0 -> Have Children, No? Evaluate:
Object 0, Object 0 = 2
Any other elements in this array? Yes
Object 0, Object 1 = 9
Any other elements in this array? No
So
Object 0 = 9
Any other elements in this array? Yes
Object 1 = 90
Any other elements in this array? Yes
Object 2 = 77
Any other elements in this array? No
Expression = 77
Sean
Some days when I think about the next 30 years or so of my life I am going to spend writing code, I happily contemplate stepping off a curb in front of a fast moving bus.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|