#include <iostream> #include <vector> #include <math.h> //c1: (((A,B),C),D) //c2: ((A,B),(C,D)) std::vector< std::vector<double> > permutaionSet; void swap(double* left, double* right){ double temp; temp = *left; *left = *right; *right = temp; } int permutaion(double *input,int depth, int len){ if(depth > len){ std::cout << "input error!" << std::endl; return -1; } if(depth == len){ std::vector<double> temp(input,input+len); permutaionSet.push_back(temp); return permutaionSet.size(); } for(int i=depth; i<len; i++){ swap(input+depth,input+i); permutaion(input,depth+1,len); swap(input+depth,input+i); } return -2; } char op[] = {'+', '-', '*', '/'}; double calculator(double left, double right, char op){ switch (op) { case '+': return left+right; case '-': return left-right; case '*': return left*right; case '/': return left/right; default: return 0; } } //c1: (((A,B),C),D) double operatoration(int first_op, int second_op, int third_op,std::vector<double>& numbers){ return calculator( calculator( calculator(numbers[0],numbers[1],op[first_op]), numbers[2],op[second_op]), numbers[3],op[third_op]); } //c2: ((A,B),(C,D)) double operatoration2(int first_op, int second_op, int third_op,std::vector<double>& numbers){ return calculator( calculator(numbers[0],numbers[1],op[first_op]), calculator(numbers[2],numbers[3],op[third_op]), op[second_op]); } #define EPSSLON 0.000001 bool judge(const int itorator){ std::vector<double> temp(permutaionSet[itorator]); for(int i=0; i<4; i++) for(int j=0; j<4; j++) for(int k=0; k<4; k++) if( (fabs(24-operatoration(i,j,k,temp)) <= EPSSLON ) || (fabs(24-operatoration2(i,j,k,temp)) <= EPSSLON ) ) return true; return false; } bool Game24Points(int a, int b, int c, int d){ double input[4]; double *ptr = input; *ptr++ = a, *ptr++ = b, *ptr++ = c, *ptr++ = d; permutaionSet.clear(); permutaion(input,0,4); for(size_t i=0; i<permutaionSet.size(); i++) if(judge(i)) return true; return false; } int _tmain(int argc, _TCHAR* argv[]){ std::cout << Game24Points(7,7,7,7) << " "<< Game24Points(1,2,3,4) << " " << Game24Points(7,2,1,10); system("pause"); return 0; }
算法的思想是:
24点算法是4个数字之间通过,加、减、乘、除、括号使得最终的结果为24.
先将4个数字进行一次全排列,这个全排列包括了4个数字的所有出现顺序。
选择一种排列,对这4个数字进行括号操作,总共有一下两种括号操作形式:
//c1: (((A,B),C),D)
//c2: ((A,B),(C,D))最后将上面两个式子中加上运算符(式子中逗号的位置换上运算符),判断结果是否为24
相关推荐
NULL 博文链接:https://andyjojo.iteye.com/blog/319531
24点算法用于计算24点,与平常的游戏没有区别
24点算法的实现.24点算法的实现.24点算法的实现.
C++ 递归实现24点算法, 输入数组,返回所有可以组成24点的结果,并且自动去重 结果为算式 如: (2+10)*2*1=24
24点算法及程序,利用javascript的一个方法来实现。
24点算法的源代码,可以编写课程设计。里面有源程序 。
java 扑克牌24点算法 输入4个数(1-10),可以得到用+-*/运算,结果为24的方法
这是C#的控制台程序,用不到70行代码解决了24点游戏的算法问题。给出4个数字,能够计算4个数字加减乘除后得到24的所有式子。代码里对括号进行了处理。
一个java24点算法
给定任意四个整数,自动给出一个计算公式,可计算出结果为24。
24点算法,穷举12288种可能,不正确你抽我。
24点算法C++描述,实现了在苛地可在载在地呀兴鸿恩;一 一 圾 有发一有工发参基圾一了东盟
完整实现24点算法程序,便于了解24点算法,直接运行。
24点算法小程序,当然你也可以根据需要改成你自己的点数。
自己写的24点算法,能够计算出 3 3 8 8 等包含分数算法的程序,速度比较快
算24点 算法经典 回溯法 简单实现,简单改一下格式,就要成为自己的了!
24点算法介绍.doc
24点算法大全.doc
24点算法大全.pdf