您的位置:首页 > 其它

OJ 系列之24点游戏算法

2016-01-21 17:11 531 查看

1、问题描述



2、解题思路

没找到好的办法,采用穷举法。所谓穷举法就是列出4个数字加减乘除的各种可能性。我们可以将表达式分成以下几种:首先我们将4个数设为a,b,c,d,,将其排序列出四个数的所有排序序列组合(共有A44=24种组合)。再进行符号的排列表达式,其中算术符号有加、减、乘、除。其中有效的表达式有:

if(a+b+c+d==24)
return 1;
else if(a+b+c-d==24)
return 1;
else if((a+b)*(c+d)==24)
return 1;
else if((a-b)*(c+d)==24)
return 1;
else if((a-b)*(c-d)==24)
return 1;
else if((a+b+c)*d==24)
return 1;
else if((a+b-c)*d==24)
return 1;
else if((a-b-c)*d==24)
return 1;
else if((a*b*c)/d==24)
return 1;
else if((a*b)*(c-d)==24)
return 1;
else if((a*b)*c-d==24)
return 1;
else if((a*b)*c+d==24)
return 1;
else if(a*b*c*d==24)
return 1;
else if((a+b)*(c/d)==24)
return 1;
else if((a+b)+(c/d)==24)
return 1;
else if((a*b)+c+d==24)
return 1;
else if((a*b)+c-d==24)
return 1;
else if((a*b)-(c/d)==24)
return 1;
else if((a*b)+(c/d)==24)
return 1;
else if((a*b)-c-d==24)
return 1;
else if((a*b)+(c*d)==24)
return 1;
else if((a*b)-(c*d)==24)
return 1;
else if((a*b)/(c*d)==24)
return 1;
else if((a*b)/(c+d)==24)
return 1;
else if(c!=d)
if((a*b)/(c-d)==24)
return 1;


首先列出所有有效的表达式,其中a,b,c,d的范围是1到10。下面我介绍下穷举法的主要实现,我们知道要实现24点的算法,就是通过4个数字,4个运算符号和2对括号(最多为2对),通过各种组合判断其结果是否为24。我们用a,b,c,d代替4个数字。通过变换其不同的排列组合,依次判断其结果是否为24。

3、代码实现

include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int check(int a,int b,int c,int d)
{
if(a+b+c+d==24) return 1; else if(a+b+c-d==24) return 1; else if((a+b)*(c+d)==24) return 1; else if((a-b)*(c+d)==24) return 1; else if((a-b)*(c-d)==24) return 1; else if((a+b+c)*d==24) return 1; else if((a+b-c)*d==24) return 1; else if((a-b-c)*d==24) return 1; else if((a*b*c)/d==24) return 1; else if((a*b)*(c-d)==24) return 1; else if((a*b)*c-d==24) return 1; else if((a*b)*c+d==24) return 1; else if(a*b*c*d==24) return 1; else if((a+b)*(c/d)==24) return 1; else if((a+b)+(c/d)==24) return 1; else if((a*b)+c+d==24) return 1; else if((a*b)+c-d==24) return 1; else if((a*b)-(c/d)==24) return 1; else if((a*b)+(c/d)==24) return 1; else if((a*b)-c-d==24) return 1; else if((a*b)+(c*d)==24) return 1; else if((a*b)-(c*d)==24) return 1; else if((a*b)/(c*d)==24) return 1; else if((a*b)/(c+d)==24) return 1; else if(c!=d) if((a*b)/(c-d)==24) return 1;
else
return 0;
return 0;

}

bool Game24Points(int a, int b, int c, int d)
{
//TODO: Add codes here ...
if(a<=0||a>10||b<=0||b>10||c<=0||c>10||d<=0||d>10)
return false;

int source[4];
source[0]=a;
source[1]=b;
source[2]=c;
source[3]=d;

vector<int> sort1(source,source+4);
if(check(sort1[0],sort1[1],sort1[2],sort1[3])==1) {
return true;
}

sort(sort1.begin(),sort1.end());
/*next_permutation 重新全排列*/
while (next_permutation(sort1.begin(), sort1.end())) {
if(check(sort1[0],sort1[1],sort1[2],sort1[3])==1) {
return true;
}
// cout<<sort1[0]<<" "<<sort1[1]<<" "<<sort1[2]<<" "<<sort1[3]<<endl;

}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  OJ 24点游戏算法