I'm trying to write code for a very basic version of the game 24. This code will receive either two, three, or four integers and determine if there is any way that these numbers can add, subtract, multiply or divide to the number 24. Locations of parenthesis can change as well. I handled the two integer case easily, and now am working on the three integer case and so far have the following function.
The above compiles correctly, but when it is run I get "floating point exception." I've read through some posts on the forum and this error is typically the result of a divide by zero or invalid array address. I am thinking that my problem is of the latter, because I have just started using arrays and am not too sure how to use them properly.
Any suggestions to improve this algorithm are welcome as well, Thanks!
EDIT: Sorry for posting the snippet, I realized after that thats not the right way to post.
bool makeSumQ(int num1, int num2, int num3)
{
bool ans;
int a[6], b[6], c[6], d[36], e[36], f[36];
alg(num1, num2, a, 0);
alg(num1, num3, b, 0);
alg(num2, num3, c, 0);
for (int i = 0; i < 6; i++)
{
alg(num3, a[i], d, i);
alg(num2, b[i], e, i);
alg(num1, c[i], f, i);
}
for (int i = 0; i < 36; i++){
if ((d[i] == 24) || (f[i] == 24) || (c[i] == 24))
{
ans = true;
break;
}
else
{
ans = false;
}
}
return ans;
}
//Function finds all six poss combinations of the variable
void alg(int num1, int num2, int poss[], int iteration){
int address = iteration * 6;
poss[0 + address] = num1 + num2;
poss[1 + address] = num1 - num2;
poss[2 + address] = num2 - num1;
poss[3 + address] = num1 * num2;
poss[4 + address] = num1 / num2;
poss[5 + address] = num2 / num1;
}
bool makeSumQ(int num1, int num2, int num3)
{
bool ans;
//Define the arrays to store the results of the operations
int a[6], b[6], c[6], d[36], e[36], f[36];
//Calculate every possible outcome for two of the three numbers
alg(num1, num2, a, 0);
alg(num1, num3, b, 0);
alg(num2, num3, c, 0);
//Plug each of the results from the previous operation back into the alg function to find all possible
//totals for three numbers
for (int i = 0; i < 6; i++)
{
alg(num3, a[i], d, i);
alg(num2, b[i], e, i);
alg(num1, c[i], f, i);
}
//Test to see if 24 is in any of the possible solutions
for (int i = 0; i < 36; i++){
if ((d[i] == 24) || (f[i] == 24) || (c[i] == 24))
{
ans = true;
break;
}
else
{
ans = false;
}
}
return ans;
}
void alg(int num1, int num
return ans;2, int poss[], int iteration){
int address = iteration * 6;
poss[0 + address] = num1 + num2;
poss[1 + address] = num1 - num2;
poss[2 + address] = num2 - num1;
poss[3 + address] = num1 * num2;
poss[4 + address] = num1 / num2;
poss[5 + address] = num2 / num1;
}