大家一起来玩游戏-24点(递归)

 

#include <stdio.h>
#include <math.h>
void fuhao(int temp[], char ch[], int pos,int num[]);
int cal(int temp[], char ch[], int num[]);

char a[4] = {'+', '-', '*', '/'};
int flag = 0;//判断是否已有满足24点的情况

//对4个数的位置进行排序,共有24种情况
void sort(int num[], int temp[], int pos)
{
    if (pos == 4) {
        char ch[3];
        //4个数排序好后,开始选择运算符
        fuhao(temp, ch, 0, num);
        return;
    }
    for (int i = 0; i < 4; i++) {
        int j;
        for (j = 0; j < pos; j++) if (i == temp[j]) break;
        if(j == pos) {
            temp[pos] = i;
            sort(num, temp, pos + 1);
            if (flag == 1) return;
        }
    }
}

//选择3个符号插入4个数之间
void fuhao(int temp[], char ch[], int pos, int num[])
{
    if (pos == 3) {
        //选择好后,计算该表达式是否满足24点
        //满足则返回1,不满足则返回0
        //返回为1时,flag=1,表示已找到满足24的情况
        if (cal(temp, ch, num)) flag = 1;
        return;
    }
    for (int i = 0; i < 4; i++) {
        ch[pos] = a[i];
        fuhao(temp, ch, pos + 1,num);
        if (flag == 1) return;
    }
}

double suan(double a, double b, char hao)
{
    switch (hao)
    {
    case '+': return a + b;
    case '-': return a - b;
    case '*': return a * b;
    case '/': return a * 1.0 / b;
    }
}

//对该表达式的所有可能运算顺序进行计算,共有5种情况
int cal(int temp[], char ch[],int num[])
{
    double res;
    //(((①②) ③) ④)
    res = suan(num[temp[0]], num[temp[1]], ch[0]);
    res = suan(res, num[temp[2]], ch[1]);
    res = suan(res, num[temp[3]], ch[2]);
    if (fabs(res - 24) < 1e-12) return 1;
    //((① (②③)) ④)
    res = suan(num[temp[1]], num[temp[2]], ch[1]);
    res = suan(num[temp[0]], res, ch[0]);
    res = suan(res, num[temp[3]], ch[2]);
    if (fabs(res - 24) < 1e-12) return 1;
    //((① ((②③) ④)
    res = suan(num[temp[1]], num[temp[2]], ch[1]);
    res = suan(res, num[temp[3]], ch[2]);
    res = suan(num[temp[0]], res, ch[0]);
    if (fabs(res - 24) < 1e-12) return 1;
    //(① (② (③④)))
    res = suan(num[temp[2]], num[temp[3]], ch[2]);
    res = suan(num[temp[1]], res, ch[1]);
    res = suan(num[temp[0]], res, ch[0]);
    if (fabs(res - 24) < 1e-12) return 1;
    //((①②) (③④))
    res = suan(num[temp[0]], num[temp[1]], ch[0]);
    res = suan(res, suan(num[temp[2]], num[temp[3]], ch[2]), ch[1]);
    if (fabs(res - 24) < 1e-12) return 1;
    return 0;
}

int main()
{
    int n;
    scanf("%d", &n);
    while (n--) {
        int num[4], temp[4];
        for (int i = 0; i < 4; i++) scanf("%d", &num[i]);
        sort(num, temp, 0);
        if (flag == 1) {
            printf("True");
            flag = 0;
        }
        else printf("False");
        if (n != 0) printf(" ");
    }
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值