C++编写一个算24点的小工具

一个初中小伙伴问的问题,采用暴力+回溯,参考了leetcode的部分题解
#include<iostream>
#include<cmath>
#include<cstring>
#include <sstream>
using namespace std;
double calculate(double x,double y,int opt);
int card[4];
double temp[4];
bool found = false;
void solve(int n);
int point = 0;
string ans[10];
string double2string(double do_b);
int main(){
    cout << "请输入四张牌"<<endl;
    cin >> card[0] >> card[1] >> card[2] >> card[3];
    for(int k = 0; k < 4 ; k ++){    //将数据保存一下以便回溯
        temp[k] = card[k];
    }
    solve(4);  //递归入口

    if(found){
        for(int i = 0 ; i < 4 ; i ++){
            cout << ans[i] << endl;
        }
    }else{
        cout << "无法计算24" << endl;
    }
    return 0;
}

void solve(int n){
    double backup[4];

    if(n == 1){
        if(abs(24 - temp[0]) < 1e-6){
            found = true;
        }
        return;
    }

    for(int i = 0 ; i < n ; i ++){
        for(int j = 0; j < n ; j ++){
            if(i != j){
                for(int opt = 0; opt < 4 ; opt ++){     //进行四则运算
                    for(int k = 0; k < 4 ; k ++){    //将数据保存一下以便回溯
                        backup[k] = temp[k];
                    }
                    temp[i] = calculate(temp[i] , temp[j], opt);
                    temp[j] = temp[n - 1];
                    point = point + 1;
                    solve(n - 1);
                    if(found) return;
                    for(int k = 0; k < 4 ; k ++){    //回溯
                        temp[k] = backup[k];
                    }
                    point = point - 1;

                }
            }
        }
    }
}

double calculate(double x,double y,int opt){//进行四则运算
    switch (opt) {
        case 0:
            ans[point] = double2string(x) + " + " + double2string(y) + " = " + double2string(x + y);
            return x + y;
        case 1:
            ans[point] = double2string(x) + " - " + double2string(y) + " = " + double2string(x - y);
            return x - y;
        case 2:
            ans[point] = double2string(x) + " * " + double2string(y) + " = " + double2string(x * y);
            return x * y;
        case 3:
            ans[point] = double2string(x) + " / " + double2string(y) + " = " + double2string(x / y);
            return x / y;
    }

    return 0;
}
string double2string(double do_b)

{
    string str1;
    stringstream sstr;
    sstr<<do_b;
    sstr>>str1;
    return str1;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值