1.16 24点游戏
2012-07-30 11:47
363 查看
24点游戏的解决办法,也是采取穷举法的思路,4个数,有4!=24中排列的方法,然后3个操作符号,有4×4×4 = 64种结果,再加上括号,有5种结果,于是,每4个数有24*66*5 = 7680中结果。
为了简便计算,原书中给出的第一种方法采取这样一种递归的思路:
为了简便计算,原书中给出的第一种方法采取这样一种递归的思路:
/* <编程之美> 深搜 遍历运算符, 数和括号的所有排列形式 */ #include <iostream> #include <string> #include <math.h> using namespace std; const double Threshold = 1e-6; const int CardsNumber = 4; const int ResultValue = 24; double number[CardsNumber]; string result[CardsNumber]; bool PointGame(int n) { if(n == 1) { if(fabs(number[0] - ResultValue) < Threshold) { cout << result[0] << endl; return true; } else { return false; } } for(int i = 0; i < n; i++) { for(int j = i +1 ; j < n; j++) { double a, b; string expa, expb; a = number[i]; b = number[j]; number[j] = number[n - 1]; expa = result[i]; expb = result[j]; result[j] = result[n-1]; //+加法操作 a+b number[i] = a + b; result[i] = '(' + expa + '+' + expb + ')'; if(PointGame(n-1)) { return true; } //减法操作 a-b number[i] = a - b; result[i] = '(' + expa + '-' + expb + ')'; if(PointGame(n-1)) { return true; } //减法操作 b-a number[i] = b - a; result[i] = '(' + expb + '-' + expa + ')'; if(PointGame(n-1)) { return true; } //乘法操作 a*b number[i] = a * b; result[i] = '(' + expa + '*' + expb + ')'; if(PointGame(n-1)) { return true; } //除法操作 a/b, 如果除数不为0 if(b != 0) { number[i] = a / b; result[i] = '(' + expa + '/' + expb + ')'; if(PointGame(n-1)) { return true; } } //除法操作 b/a , 如果除数不为0 if(a != 0) { number[i] = b / a; result[i] = '(' + expb + '/' + expa + ')'; if(PointGame(n-1)) { return true; } } number[i] = a; number[j] = b; result[i] = expa; result[j] = expb; } } return false; } int main() { int x; for(int i =0; i< CardsNumber; i++) { char buffer[20]; cout << "the " << i << "the number: "; cin >> x; number[i] = x; itoa(x,buffer,10); result[i] = buffer; } if(PointGame(CardsNumber)) { cout << "Success" << endl; } else { cout << "failure" << endl; } system("pause"); return 0; }
相关文章推荐
- 编程之美 1.16 24点游戏
- 编程之美 1.16 24点游戏
- 1.16 24点游戏
- 编程之美 1.16 24点游戏
- 编程之美--1.16 24点游戏
- 《编程之美》读书笔记22: 1.16 24点游戏
- [编程之美] PSet1.16 24点游戏
- 《编程之美》读书笔记22: 1.16 24点游戏(补充)
- 编程之美-1.16 24点游戏
- 编程之美1.16——24点游戏
- 读书笔记之编程之美 - 1.16 24点游戏
- 编程之美: 第一章 1.16 24点游戏
- 1.16 24点游戏
- 编程之美:第一章 1.16 24点游戏
- 1.16 24点游戏
- UESTC 1252 24点游戏 DFS
- 24点游戏探秘系列2:唯一解的情况
- ACDREAM 05C 哗啦啦族的24点游戏(DFS专场)
- 24点游戏
- OJ 系列之24点游戏算法