C++实现24点算法

来源:互联网 发布:numpy 矩阵列归一化 编辑:程序博客网 时间:2024/06/05 19:54

24点游戏应该很多人都不陌生,本算法是判断4个数字,是否能通过加,减,乘,除和括号进行运算得到24.(其中这4个数的顺序是固定的)


首先,可以假设这4个数字为a,b,c,d. 

由于顺序固定,在不考虑括号的情况,运算式的形式为:a # b # c # d(#表示加减乘除运算符)。

接下来,考虑括号,在运算符号确定时,有下面这5种情况:

1.((a#b)#c)#d

2.(a#(b#c))#d

3.a#((b#c)#d)

4.(a#b)#(c#d)

5.a#(b#(c#d))


因此,可以得出下面的算法。(算法实现很简明易懂,不过效率一般)

int Add(int a, int b){     return a+b;}int Sub(int a, int b){     return a-b;}int Mul(int a, int b){     return a*b;}int Div(int a, int b){     if(b == 0)          return -10000;//返回一个足够小的数字     return a/b;}int(*op[4])(int,int) = {Add, Sub, Mul, Div};//函数指针。C++确实强大bool Game24Points(int a, int b, int c, int d){     for(int i=0; i<4; i++)// a,b之间的运算     {          for(int j=0; j<4; j++)// b,c之间的运算          {               for(int k=0; k<4; k++)// c,d之间的运算               {                    //((a#b)#c)#d                    int ret = op[k](op[j](op[i](a, b), c) , d);                    if(ret == 24)                         return true;                    //(a#(b#c))#d                    ret = op[k](op[j](a, op[i](b, c)) , d);                    if(ret == 24)                         return true;                    //a#((b#c)#d)                    ret = op[k](a, op[j](op[i](b, c) , d));                    if(ret == 24)                         return true;                    //(a#b)#(c#d)                    ret = op[k](op[i](a, b), op[j](c, d));                    if(ret == 24)                         return true;                    //a#(b#(c#d))                    ret = op[k](a, op[j](b, op[i](c, d)));                    if(ret == 24)                         return true;               }          }     }     return false;}

0 0
原创粉丝点击