《编程之美》1.16 24点游戏
输入:n1,n2,n3,n4。输出:若能得到运算结果为24,则输出一个对应的运算表达式,否则输出0。例如:输入11,8,3,5,则输出为:(11-8)*(3+5)=24。
思想:四个数总共有五种结合方式,即A(B(CD))、A((BC)D)、(AB)(CD)、(A(BC))D、((AB)C)D,而我把这五种次序存入保存计算顺序的二维数组sequence中,每次传入一个sequence[i],遍历五次就能把所有情况都计算进去。为了得到最后的表达式,用字符串来表示最后的结果,先用','来表示可能的运算符,从而构造一个表达式A,(B,(C,D))然后传入进行计算。
#include<iostream>
#include<vector>
#include<string>
using namespace std;
bool twantifourPoint(vector<double> &inputDate,vector<int> sequence,string &s)
{
if(inputDate.size()==1)
{
if(abs(inputDate.front()-24)<1e-9)
return true;
else
return false;
}
int first=sequence[0];//计算当前的两个数
int second=sequence[0]+1;
char ch;
for(int i=0;i<4;i++)//每次都有四次运算
{
vector<double> temp(inputDate);
switch(i)
{
case 0:
ch='+';
temp[first]+=temp[second];
break;
case 1:
ch='-';
temp[first]-=temp[second];
break;
case 2:
ch='*';
temp[first]*=temp[second];
break;
case 3:
ch='/';
temp[first]/=temp[second];
break;
default:
break;
}
temp.erase(temp.begin()+second);
int j=0;
const int N=s.size();
for(j=first;j<N;j++)
if(s[j]==',')
{
s[j]=ch;
break;
}
if(twantifourPoint(temp,vector<int>(sequence.begin()+1,sequence.end()),s))
return true;
s[j]=',';
}
return false;
}
bool isValid(vector<double> &inputDate)
{
int A[15]={2,1,0,1,1,0,0,1,0,1,0,0,0,0,0};
int B[20]={2,5,9,10,2,3,7,10,0,4,6,10,0,3,7,8,0,1,5,8};//存放括号在s中的位置
char C[20]={'(','(',')',')','(','(',')',')','(',')','(',')','(','(',')',')','(','(',')',')'};
vector<vector<int> >sequence;//保存5次计算的计算顺序
sequence.push_back(vector<int>(A,A+3));//对应A(B(CD))
sequence.push_back(vector<int>(A+3,A+6));//对应A((BC)D)
sequence.push_back(vector<int>(A+6,A+9));//对应(AB)(CD)
sequence.push_back(vector<int>(A+9,A+12));//对应(A(BC))D
sequence.push_back(vector<int>(A+12,A+15));//对应((AB)C)D
char *ch=new char[10];
for(int i=0;i<5;i++)
{
string temp;//保存每次计算的计算结果,类似于A,(B,(C,D))的形式
int k=i*4,m=0;
for(int j=0;j<11;j++)
{
if(j==B[k])
temp+=C[k++];
else
{
if(m&1)
temp+=',';//逗号用来表示可能的运算符的位置
else
{
itoa(inputDate[m>>1],ch,10);
temp+=ch;
}
m++;
}
}
if(twantifourPoint(inputDate,sequence[i],temp))
{
temp+="=24";
cout<<temp<<endl;
return true;
}
}
return false;
}
int main()
{
const int N=4;
double A[N]={10,10,4,4};
vector<double> inputDate(A,A+N);
cout<<isValid(inputDate)<<endl;
system("pause");
return 0;
}