I\'m trying to learn more about algorithm design, and I\'ve set myself the challenge of creating a simple game that presents users with an array of numbers, a target number,
Enumerate all possible expressions. For numbers 1,2,3,and operator + and - ,you can get:1+2+3,1+2-3,1-2+3,1-2-3.
Evaluate all possible expressions.
You are facing a more generalized problem of the Partition Problem, which is NP-Complete.
The Partition Problem is: Given n
numbers, split them into two (distinct) groups A
and B
such that sum(A) = sum(B)
. Now, it is easy to see that if you have a problem with +,- operators and target number 0 - this is basically the same problem, and there is an immidiate reduction from Partition Problem to your problem.
From this we can conclude your problem is NP-Hard as well, and there is no known polynomial solution for your problem.
Alternatives are:
Sorry if it's bad news -but at least you won't be looking for something that (most computer scientists believe) is not there
Here is a Java solution from programcreek.
public static boolean isReachable(ArrayList<Integer> list, int target) {
if (list == null || list.size() == 0)
return false;
int i = 0;
int j = list.size() - 1;
ArrayList<Integer> results = getResults(list, i, j, target);
for (int num : results) {
if (num == target) {
return true;
}
}
return false;
}
public static ArrayList<Integer> getResults(ArrayList<Integer> list,
int left, int right, int target) {
ArrayList<Integer> result = new ArrayList<Integer>();
if (left > right) {
return result;
} else if (left == right) {
result.add(list.get(left));
return result;
}
for (int i = left; i < right; i++) {
ArrayList<Integer> result1 = getResults(list, left, i, target);
ArrayList<Integer> result2 = getResults(list, i + 1, right, target);
for (int x : result1) {
for (int y : result2) {
result.add(x + y);
result.add(x - y);
result.add(x * y);
if (y != 0)
result.add(x / y);
}
}
}
return result;
}