Task
Given a list of numbers
For instance:
1, 2, 3.
Get each combination of these numbers using the operations of multiplication or addition (* / +)
So in the above example the combination would be
1 + 2 + 3
1 + 2 * 3
1 * 2 * 3
1 * 2 + 3
Ive written a basic recursive method to solve it, since I thought about it as follows
Given the number, I can either
Add the following number
Multiply the next number
So you get a tree like this
START NUMBER
/ \
* +
/ \ / \
* + * +
Etc ...
But the output displays each answer twice
The output that I get when using 1,2,3 is
1 * 2 + 3
1 * 2 + 3
1 * 2 * 3
1 * 2 * 3
1 + 2 + 3
1 + 2 + 3
1 + 2 * 3
1 + 2 * 3
My question
Is this an acceptable algorithm, and if so, what happens to my code
Is there an even more efficient way to do this.
CODE
package AG;
import java.util.LinkedList;
import java.util.Stack;
public class ArithmeticGame {
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
LinkedList<Integer> number = new LinkedList<>();
for (int i = 1; i <= 3; i++) {
numbers.add(i);
}
permutateSigns('*', numbers, 0, "");
permutateSigns('+', numbers, 0, "");
}
public static void permutateSigns(char operation, LinkedList<Integer> number, int pos, String expresion) {
double sum = 0;
if (pos == number.size()-1) {
expresion += number.get(pos);
System.out.println(expresion);
} else {
expresion += (Integer.toString(number.get(pos)) + Character.toString(operation));
permutateSigns('+', number, pos + 1, expresion);
permutateSigns('*', number, pos + 1, expresion);
}
}
}