Count 24 (recursive) - Learning Algorithm

problem

4 to 10 is given a small positive integer, you can use the arithmetic operations, and comprises four kinds of
numbers put together to give a number of connections 4 expression. The question now is whether there is
in a manner such that the resulting expression equal to 24.
Here priority operation and the results of operations of addition, subtraction and brackets with our usual
definition is consistent (division defined here is the real division).
For example, for 5,5,5,1, we know 5 * (5 - 1/5) = 24, and therefore
can be 24. As another example, for 1,1,4,2, how we can not get
24

Entry

The input data includes a plurality of rows, each row is given a set of test data, including 10 in the four small positive integer. Finally, a set of test data comprises four 0, indicating the end of input, the set of data is not processed.

Export

For each set of test data, output a line 24 can be obtained if the output "YES"; otherwise, the output "NO".

Sample input

5 5 5 1
1 1 4 2
0 0 0 0

Sample Output

YES
NO

Thinking

24 count the number n, the two numbers must first operator. The results of these two numbers counted, and the number of the remaining n-2, n-1 constitute the required number of 24 questions
two enumerator first calculated, and an operation mode of these two numbers.
Boundary conditions: a count number 24
Note: Floating-point comparison for equality can not ==

Code


#include <iostream>
#include <cmath>
using namespace std;
double a[5];
#define EPS 1e-6
bool isZero(double x) {
return fabs(x) <= EPS; 
}
bool count24(double a[],int n) 
{//用数组a里的 n个数,计算24
if( n == 1 ) {
if(isZero( a[0] - 24) )
return true;
else
return false;
}

double b[5];
for(int i = 0;i < n-1; ++i)
for(int j = i+1;j < n; ++j) { //枚举两个数的组合
int m = 0; //还剩下m个数, m = n - 2
for(int k = 0; k < n; ++k) 
if( k != i && k!= j)
b[m++] = a[k];//把其余数放入b
b[m] = a[i]+a[j];
if(count24(b,m+1))
return true;
b[m] = a[i]-a[j];
if(count24(b,m+1))
return true;
b[m] = a[j]-a[i];
if(count24(b,m+1))
return true;
b[m] = a[i]*a[j];
if(count24(b,m+1))
return true;

if( !isZero(a[j])) {
b[m] = a[i]/a[j];
if(count24(b,m+1))
return true;
}
if( !isZero(a[i])) {
b[m] = a[j]/a[i];
if(count24(b,m+1))
return true;
} }
return false;
}
int main()
{
while(true) {
for(int i = 0;i < 4; ++i)
cin >> a[i];
if( isZero(a[0]))
break;
if( count24(a,4))
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}
Published 79 original articles · won praise 133 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_45822638/article/details/105030925