r/programmingrequests • u/LastKnownWhereabouts • Nov 17 '17
[REQUEST] Java program that outputs all possible results of a user-given equation, ignoring order of operations
I'm trying to build a calculator that does as the title says. For example, if the user inputs 4*2+3, the program will output "11, 20". However, I'm having a hard time figuring out where to start with this. Currently, my plan is to add each number and operator (I'll only need +,-, and *) to an ArrayList, each of them being a new element. However, I don't know what to do from there to get the math right. There is no limit to how long the equation can be, which has stopped some of my ideas for handling this.
Thanks!
2
Upvotes
2
u/serg06 Nov 18 '17
Let's say you put all your numbers and all your operators in an arraylist. So 5*4+2/7+3 looks like this:
nums = [5, 4, 2, 7, 3]
ops = [*, +, /, +]
Then it gets fun:
number each operator, so you get an array [0, 1, 2, 3]
find all permutations of the numbers (google java array permutation code if you need it)
for each permutation, execute the operations in that order
for example, let's say you're on the permutation [1, 3, 0, 2], then apply the operators like so:
Take the first number in the permutation (the 1)
Find the correct operator (ops[1])
Do nums[1] = nums[1] + nums[2] (because ops[1] is a +, and it goes between nums at index 1 and 2)
Delete nums[2] from nums
Delete ops[1] from ops
Edit: Also, for all numbers in the permutation that are greater than the one you're on (i.e. greater than 1), decrement them by 1
Continue to the next number in the permutation
Eventually you'll be left with an empty permutation and a single number in nums. The rest is semantics.
Edit: Added an important step