In: Computer Science
C language plzzzzzz
Calc24isafamousmathgame. Now w would like to implement an advanced Calc24 calculator. Given n integers, you need to verify whether 24 can be deduced with these numbers and four basic operators: ‘+’. ‘-’, ‘*’ and ‘/’. Note that every number can only be used once. Input The first line with two integers: n,t , where n denotes the number of integers in each group, t indicates the total number of groups that you need to verify. In following t lines, each represent n integers in that group. Output will be t lines. Each line prints either true or false, indicating whether 24 can be deduced from the corresponding line of input.
Sample input
4 3
2 4 10 10
4 6 1 1
1 1 1 1
[Output]
true
true
false
//As no logic difference and much syntax difference, writing the code in c++
vector<double> get(double a, double b) {
vector<double> res;
for(int op = 0; op < 4; ++op) {
switch(op) {
case 0:
res.push_back(a*b);
break;
case 1:
res.push_back(a/b);
res.push_back(b/a);
break;
case 2:
res.push_back(a+b);
break;
case 3:
res.push_back(a-b);
res.push_back(b-a);
break;
}
}
return res;
}
double eps = 0.000000001;
bool match(double x) {
return abs(x-24.0) < eps;
}
bool judgePoint24(vector<int>& nums) {
bool ans = false;
sort(nums.begin(), nums.end());
do {
// 1st and 2nd
vector<double> _12 = get(1.0 * nums[0], 1.0 * nums[1]);
// 3rd and 4th
vector<double> _34 = get(1.0 * nums[2], 1.0 * nums[3]);
// check _12 and _34
for(double x: _12) {
for(double y: _34) {
vector<double> res = get(x, y);
for(double z: res)
if(match(z))
ans = true;
}
}
vector<double> _123;
// _12 and nums[2]
for(double x: _12) {
vector<double> r = get(x, 1.0 * nums[2]);
_123.insert(_123.end(), r.begin(), r.end());
}
// _123 and nums[3]
vector<double> _1234;
for(double x: _123) {
vector<double> r = get(x, 1.0 * nums[3]);
_1234.insert(_1234.end(), r.begin(), r.end());
}
for(double z: _1234)
if(match(z))
ans = true;
} while(next_permutation(nums.begin(), nums.end()));
return ans;
}