AVC
AVC

Reputation: 77

Mathematical Expressions Solving Algorithm

My previous question was put on hold as question was not clear.

Posting it again with specific query

My requirement is to solve any mathematical complex expressions using PHP. For example,

If I have a string "1(1+2)/3 + 4", using BODMAS rule, I have to solve it. But I have to also get all individual steps.

Two sites I have referred are:
http://www.careerbless.com/calculators/ScientificCalculator/
http://web2.0calc.com/

My first question is , which is the ideal language for these kind of problems. Also, is there any built in solution available so that I don't have to reinvent the wheel

Thanks in advance

Upvotes: 0

Views: 1394

Answers (1)

viniciuswebdev
viniciuswebdev

Reputation: 1346

Stacks may help you, consider: 1 + (2 + 3)

Create two stacks, one of numbers, other with operators.

When you find a number, put in the stack of numbers, when you find a operator, put in the stack of operators, when you find "(" do nothing, and when you find a ")", get two numbers of a stack and one operator, do the calc of these two numbers and put again in the stack of numbers, see the code loop:

//1 + (2 + 3)
operators = []
numbers = []

//I put the number in the numbers stack
//+ (2 + 3)
operators = []
numbers = [1]
-- 
// I put the operator in the operators stack
// (2 + 3)
operators = [+]
numbers = [1]
-- 
// 2 + 3)
//find a "(" char, do nothing
operators = [+]
numbers = [1]
-- 
// + 3)
operators = [+]
numbers = [1, 2]
-- 
// 3)
operators = [+, +]
numbers = [1, 2]
-- 
// )
operators = [+, +]
numbers = [1, 2, 3]
--
//found a ")", get two items of stack of numbers (3,2), and one item of operators stack (+), result is 5, put back in the stack of numbers 
operators = [+]
numbers = [1, 5]
--
//When finished string, get two elements and one operator until finish the stack
// get two elements of numbers stack (1,5) and one of operators stack +, result is 6

I hope that it help you

Upvotes: 1

Related Questions