I am currently working on a little program that's supposed to find every combination.
Fill the following place holders with digits in the range from 1 to 9. Each digit only appears once and make the equation sum up to 100.
_ / _ * _ _ * _ * _ / _ _ * _ = 100
#include <bits/stdc .h>
#include <cmath>
using namespace std;
void print(int arr[], int n){
for (int i = 0; i < n; i ){
cout << arr[i] << " ";
}
cout << endl;
}
void findCombos(int arr[], int n){
std::sort(arr, arr n);
do{
if((arr[0] / arr[1] * arr[2] arr[3] * arr[4] * arr[5] / arr[6] arr[7] * arr[8]) == 100){
print(arr, n);
}
}while(next_permutation(arr, arr n));
}
int main(){
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int size = sizeof(arr) / sizeof(arr[0]);
findCombos(arr, size);
return 0;
}
I generated 900 solutions with this code. Some of the permutations are correct, but some of the combinations do not calculate exactly to 100. My if statement is matching up the operations correctly, but why are the incorrect permutations displaying?
CodePudding user response:
You are dividing integers, which truncates the result. If you divide 9 by 2 as integers the result will be 4 and not 4.5. This means the value calculated by your program will not be correct.