1. 程式人生 > 其它 >C++實現24點生成與24點解答

C++實現24點生成與24點解答

技術標籤:⭐C/C++程式設計筆記c++

在這裡插入圖片描述

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <ctime>
using namespace std;
 
int in[5];
 
int calc(int operName, int x, int y)
{
    if (operName == 1)//+ 
    {
        return x + y;
    }
 
    if (operName == 2)//-
    {
        if
(x - y <= 0) { return -3456731; } return x - y; } if (operName == 3)//* { if (x*y <= 0) { return -464652; } return x * y; } if (operName == 4)// / { if (x*y == 0 || x < y || x % y !=
0) { return -5643212; } return x / y; } } char oper[] = { '!','+','-','*','/' }; int random() { return rand() % 12 + 1; } int main() { srand(time(NULL)); cout << "Initial numbers are: "; for (int i = 1; i <= 4; i++) {
in[i] = random(); cout << in[i] << " "; } cout << endl; sort(in + 1, in + 5); do { for (int i = 1; i <= 4; i++)//3pos,fill operator { for (int j = 1; j <= 4; j++) { for (int k = 1; k <= 4; k++) { int s1 = calc(i, in[1], in[2]); int s2 = calc(j, s1, in[3]); int s3 = calc(k, s2, in[4]); if (s3 == 24) { if (in[1] >= in[2] && s1 >= in[3] && s2 >= in[4]) { cout << in[1] << oper[i] << in[2] << '=' << s1 << endl; cout << s1 << oper[j] << in[3] << '=' << s2 << endl; cout << s2 << oper[k] << in[4] << '=' << s3 << endl; return 0; } } s1 = calc(j, in[2], in[3]); s2 = calc(i, in[1], s1); s3 = calc(k, s2, in[4]); if (s3 == 24) { if (in[2] >= in[3] && in[1] >= s1 && s2 >= in[4]) { cout << in[2] << oper[j] << in[3] << '=' << s1 << endl; cout << in[1] << oper[i] << s1 << '=' << s2 << endl; cout << s2 << oper[k] << in[4] << '=' << s3 << endl; return 0; } } s1 = calc(j, in[2], in[3]); s2 = calc(k, s1, in[4]); s3 = calc(i, in[1], s2); if (s3 == 24) { if (in[2] >= in[3] && s1 >= in[4] && in[1] >= s2) { cout << in[2] << oper[j] << in[3] << '=' << s1 << endl; cout << s1 << oper[k] << in[4] << '=' << s2 << endl; cout << in[1] << oper[i] << s2 << '=' << s3 << endl; return 0; } } s1 = calc(i, in[1], in[2]); s2 = calc(k, in[3], in[4]); s3 = calc(j, s1, s2); if (s3 == 24) { if (in[1] >= in[2] && in[3] >= in[4] && s1 >= s2) { cout << in[1] << oper[i] << in[2] << '=' << s1 << endl; cout << in[3] << oper[k] << in[4] << '=' << s2 << endl; cout << s1 << oper[j] << s2 << '=' << s3 << endl; return 0; } } s1 = calc(k, in[3], in[4]); s2 = calc(j, in[2], s1); s3 = calc(i, in[1], s2); if (s3 == 24) { if (in[3] >= in[4] && in[2] >= s1 && in[1] >= s2) { cout << in[3] << oper[k] << in[4] << '=' << s1 << endl; cout << in[2] << oper[j] << s1 << '=' << s2 << endl; cout << in[1] << oper[i] << s2 << '=' << s3 << endl; return 0; } } } } } } while (next_permutation(in + 1, in + 5)); cout << "No answer!" << endl; return 0; }