您的位置:首页 > 其它

计算 24 点是一种扑克牌益智游戏,随机抽出 4 张扑克牌,通过加 (+) ,减 (-) ,乘 ( * ), 除 (/) 四种运算法则计算得到整数 24 ,本问题中,扑克牌通过如下字符或者字符串表示,其中,小写 joker 表示小王,大写 JOKER 表示大王:

2017-06-27 16:18 1366 查看

include "stdafx.h"

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include<map>
#include<deque>
#include<stack>
using namespace std;

bool isZero(double d)
{
return fabs(d) < 1e-6;
}
stack<char> st;
bool Count24(vector<float> nums,int n)
{
if (n == 1)
{
if (isZero(nums[0]- 24))
{
//  cout << "isZero(nums[0]) - 24::" << isZero(nums[0]) - 24 << endl;
return true;
}
else
{
return false;
}
}
else
{
vector<float>temp(nums.size()-1,0);
for (int i = 2; i < nums.size(); i++)
{
temp[i - 1] = nums[i];
}

temp[0] = nums[0] + nums[1];
st.push('+');
if (Count24(temp,  n-1) == true) {return true;}
st.pop();

temp[0] = nums[0] - nums[1];
st.push('-');
if (Count24(temp, n - 1) == true) { return true; }
st.pop();

temp[0] = nums[0] * nums[1];
st.push('*');
if (Count24(temp, n - 1) == true) { return true; }
st.pop();

temp[0] = nums[0] / nums[1];
st.push('/');
if (Count24(temp, n - 1) == true) { return true; }
st.pop();
return false;
}

return false;
}

int main()
{
//cout << 'J'-11 << endl;
//cout << 'Q'-12 << endl;
//cout << 'K'-13 << endl;
//cout << 'A'-1 << endl;

string str1, str2, str3, str4;
string str;
while (true)
{
vector<float> nums;
bool result = true;
for (int i = 0; i < 4; i++)
{
cin >> str;
if (str == "joker" || str == "JOKER")
{
result = false;
break;
}
else
{
switch (str[0])
{
case 'J':nums.push_back(str[0]-63); break;
case 'Q':nums.push_back(str[0] - 69); break;
case 'K':nums.push_back(str[0] - 62); break;
case 'A':nums.push_back(str[0] - 64); break;
default:
nums.push_back(str[0] - 48);
break;
}
}
}
if (result == false)
{
cout << "ERROR" << endl;
}
else
{
bool re = false;
sort(nums.begin(), nums.end());
//      cout << "num的大小:" << nums.size() << endl;
//  for (float f : nums)cout << f << endl;
do {
if (Count24(nums, 4))
{
stack<char>temp;
re = true;
while (!st.empty())
{
temp.push(st.top());
st.pop();
}
for (int i = 0; i < nums.size()-1; i++)
{
cout << nums[i] << temp.top() ;
temp.pop();
}
cout << nums[nums.size() - 1] << endl;
break;
};
} while (next_permutation(nums.begin(),nums.end()));
if (re == false)
{
cout << "NONE" << endl;
}

}

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐