I have one given number n, 4 operands a1, a2, a3, a4, and 4 operators +, -, *, / in Java. I need to test if I can arrange operands with operators so that they form a mathematical expression which equals the given number, or at least is closest in value with it. I don't need to use all operands and each operand can be used only once. I am not asking someone to give me code just to explain if it is possible, or if there is some library for this. Thanks.
Asked
Active
Viewed 274 times
1
-
if you are asked to do so it should be possible. you might want to take a look at [this](http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form) question – SomeJavaGuy Mar 01 '16 at 13:19
-
Do you need to use each number exactly once? – Bathsheba Mar 01 '16 at 13:23
-
Yes. I forgot to mention that. – Ђорђе Ђашић Mar 01 '16 at 13:23
-
And will you use the normal rules of operator precedence? Presumably parentheses cannot be used? – Bathsheba Mar 01 '16 at 13:24
-
Yes only one given number. Normal rules. – Ђорђе Ђашић Mar 01 '16 at 13:27
-
@brso05: I launched in with an answer based on exactly that, but the OP states 4 operands. – Bathsheba Mar 01 '16 at 13:38
1 Answers
3
This is absolutely possible. You have to do all permutations possible for e-g there are two operands a,b and only one operator -
. In this case possible permutations are a-b
and b-a
. If all permutations are done and you can't get the number, there must be a result like number can't be arrived
(one of the possible output) from this function.
Here is a recursive program for doing a basic permutation. Your logic should be similar to this.
Here is a solution to execute your prepared expression and get the result