I have a problem with a operator
(+, -, /, * )
with a total sum using those operators and number of operands.
so for example i need to get total of 6 using 3 operands (1, 2, 3) and + operator, what can be the total number of permutations for that particular result.
i could not even think of the approach yet. Can anyone help me regarding that. I am using Java.
Thanks
There is a number of different methods, but to even briefly describe all of them I first need to re-read the books that I used to read in my ‘childhood’. Try this solution: create a stack that may be used to:
operations and then push the result back
This way you have a simple stack machine that allows you to perform the necessary calculations. Next you need to generate all possible permutations of concatenation of your operands and operators. When you pick up the operand from this concatenation you push it onto the stack. When you pick up the operator – you perform it. While performing operator you check that your stack has at least two elements in it – otherwise you need to skip this operator and seek for next possible operand. When you have no more operands in the concatenated sequence and you have only one element on stack – that means you completed your current calculation. so compare the result with the given result and log the sequence if needed. Then switch to the next permutation
This is definitely not optimal solution – there is a lot of possibilities to optimize. And this is most interesting part 🙂 Good luck