so as fun i decided to write a simple program that can solve the 8 Out of 10 Cats Does Countdown number puzzle, link is form Countdown, but same rules. so my program simply goes through a all possible combinations of AxBxCxDxExF, where letters are numbers and "x" are +, -, / and *. here is the code for it:
private void combineRecursive( int step, int[] numbers, int[] operations, int combination[]){
if( step%2==0){//even steps are numbers
for( int i=0; i<numbers.length; i++){
combination[ step] = numbers[ i];
if(step==10){//last step, all 6 numbers and 5 operations are placed
int index = Solution.isSolutionCorrect( combination, targetSolution);
if( index>=0){
solutionQueue.addLast( new Solution( combination, index));
}
return;
}
combineRecursive( step+1, removeIndex( i, numbers), operations, combination);
}
}else{//odd steps are operations
for( int i=0; i<operations.length; i++){
combination[ step] = operations[ i];
combineRecursive( step+1, numbers, operations, combination);
}
}
}
and here is what i use to test if the combination is what i want to not.
public static int isSolutionCorrect( int[] combination, int targetSolution){
double result = combination[0];
//just a test
if( Arrays.equals( combination, new int[]{100,'*',7,'-',8,'*',3,'+',7,'+',50})){
System.out.println( "found");
}
for( int i=1; i<combination.length; i++){
if(i%2!=0){
switch( (char)combination[i]){
case '+': result+= combination[++i];break;
case '-': result-= combination[++i];break;
case '*': result*= combination[++i];break;
case '/': result/= combination[++i];break;
}
}
if( targetSolution==result){
return i;
}
}
return targetSolution==result?0:-1;
}
so in last episode i found a problem with my code. this was the solution to one of the puzzles.
(10*7)-(8*(3+7))
i noticed that i do find this combination "10*7-8*3+7" (twice), but because i check for solutions by doing the operation left to right i actually don't find all answers. i only check for solutions like this ((((10*7)-8)*3)+7). so even though i found the combination i don't have the right order.
so now the question is how do i test all possible math orders, like (10*7)-(8*(3+7)), (10*7)-((8*3)+7) or 10*(7-8)*(3+7)? i though i can use a balance tree with operations as balancing nodes. but still i have not idea how to go through all possible combinations without moving around the formula.
(10*7)-(8*(3+7))
-
/ \
* *
/ \ / \
700 7 8 +
/ \
7 3
(10*7)-((8*3)+7)
-
/ \
* +
/ \ / \
700 7 * 7
/ \
8 3
10*(7-8)*(3+7)
*
/ \
*
/ \ 10
- +
/ \ / \
7 8 3 7
how do i do this in code? not looking for solved code more of how i should change perspective to fix it. i don't know why i am stumped at it.
about me: 4th year computer science, not new or noob at programming (i like to believe at least ;))