首页 > 试题广场 >

24点运算

[编程题]24点运算
  • 热度指数:93078 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

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

3 4 5 6 7 8 9 10 J Q K A 2 joker JOKER

本程序要求实现:输入4张牌,输出一个算式,算式的结果为24点。

详细说明:

1.运算只考虑加减乘除运算,没有阶乘等特殊运算符号,没有括号,友情提醒,整数除法要当心,是属于整除,比如2/3=0,3/2=1
2.牌面2~10对应的权值为2~10, JQKA权值分别为为1112131
3.输入4张牌为字符串形式,以一个空格隔开,首尾无空格;如果输入的4张牌中包含大小王,则输出字符串“ERROR”,表示无法运算;
4.输出的算式格式为4张牌通过+-*/四个运算符相连,中间无空格4张牌出现顺序任意,只要结果正确;
5.输出算式的运算顺序从左至右,不包含括号,如1+2+3*4的结果为24,2 A 9 A不能变为(2+1)*(9-1)=24
6.如果存在多种算式都能计算得出24,只需输出一种即可,如果无法得出24,则输出“NONE”表示无解。
7.因为都是扑克牌,不存在单个牌为0的情况,且没有括号运算,除数(即分母)的数字不可能为0

数据范围:一行由4张牌组成的字符串

输入描述:

输入4张牌为字符串形式,以一个空格隔开,首尾无空格;



输出描述:
输出怎么运算得到24,如果无法得出24,则输出“NONE”表示无解,如果输入的4张牌中包含大小王,则输出字符串“ERROR”,表示无法运算;
示例1

输入

A A A A

输出

NONE

说明

不能实现           
示例2

输入

4 2 K A

输出

K-A*4/2

说明

 A+K*2-4也是一种答案,输出任意一种即可           
示例3

输入

A 5 joker 4

输出

ERROR

说明

 存在joker,输出ERROR          
示例4

输入

K Q 6 K

输出

NONE

说明

按一般的计算规则来看,K+K-(Q/6)=24 或 K-((Q/6)-K)=24,但是因为这个题目的运算不许有括号,所以去掉括号后变为 K+K-Q/6=26-Q/6=14/6=2 或 K-Q/6-K=1/6-K=0-K=-13,其它情况也不能运算出24点,故不存在,输出NONE   

通过了,虽然是暴力方法,但是也没有十分暴力,因为题目并没有要求找到所有答案。所以总体计算量还是比较有限的。值得注意的就是,测试用例和体例有些不同,最终还是需要输出成扑克牌的符号才行。之前做成了输出数字计算式,只有65%的通过。查了好一会才找到问题所在。

'''
task24  24点计算
恭喜你通过本题
运行时间:19ms
占用内存:3612k
'''
import itertools
def is24_true(a):
    if len(a)==2:
        if a[0]+a[1] == 24:
            ops[2] = '+'
            return True
        elif a[0]-a[1] == 24:
            ops[2] = '-'
            return True
        elif a[0]*a[1] == 24:
            ops[2] = '*'
            return True
        elif a[1]!= 0 and a[0]/a[1] == 24:
            ops[2] = '/'
            return True
        else:
            return False
    elif len(a)==3:
        if (is24_true([a[0] + a[1],a[2]])):
            ops[1] = '+'
            return True
        elif (is24_true([a[0] - a[1],a[2]])):
            ops[1] = '-'
            return True
        elif (is24_true([a[0] * a[1],a[2]])):
            ops[1] = '*'
            return True
        elif (a[1]!=0) and (is24_true([a[0] / a[1],a[2]])):
            ops[1] = '/'
            return True
        else:
            return False
    elif len(a) ==4:
        if (is24_true([a[0] + a[1],a[2], a[3]])):
            ops[0] = '+'
            return True
        elif (is24_true([a[0] - a[1],a[2], a[3]])):
            ops[0] = '-'
            return True
        elif (is24_true([a[0] * a[1],a[2], a[3]])):
            ops[0] = '*'
            return True
        elif (a[1]!=0) and (is24_true([a[0] / a[1],a[2], a[3]])):
            ops[0] = '/'
            return True
        else:
            return False       
cards = ['A', '2','3', '4', '5', '6', '7', '8', '9', 'S', 'J', 'Q', 'K', 'joker', 'JOKER']
values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 'ERROR', 'ERROR']
dict_poker = dict(zip(cards, values))
dic_poker_ = dict(zip(values, cards))
while True:
    try:
        ops = ['','','']
        a = input().strip().split()
        if ('JOKER' in a) or ('joker' in a):
            print('ERROR')

        else:
            if ('10' in a):
                for i in range(len(a)):
                    if a[i] == '10':
                        a[i] = 'S'
            flag = False
            for i in itertools.permutations(''.join(a),4):
                i_ = []
                for k in i:
                    i_.append(dict_poker[k])
                if is24_true(i_):
                    #print(str(i_[0])+ops[0]+str(i_[1])+ops[1]+str(i_[2])+ops[2]+str(i_[3]))
                    for l in range(len(i_)):
                        if i_[l]=='10':
                            i_[l] = 'S'
                        i_[l] = dic_poker_[i_[l]]
                    print(str(i_[0])+ops[0]+str(i_[1])+ops[1]+str(i_[2])+ops[2]+str(i_[3]))
                    flag = True
                    break

            if not flag:
                print('NONE')
    except:
        break
发表于 2020-07-19 15:00:30 回复(2)
//24点有多种解法,测试用例答案太单一。
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;

char c[3];
bool is24(int index,float cn,int a[]){  
    if(index==4){
        if(cn==24)
            return true;
        else
            return false;
    }
    bool flag=0;
    for(int i=0;i<4;++i){
        switch(i){
            case 0:if(is24(index+1,cn+a[index],a))
                        {c[index-1]='+';flag=1;}
                   break;
            case 1:if(is24(index+1,cn-a[index],a))
                        {c[index-1]='-';flag=1;}
                   break;
            case 2:if(is24(index+1,cn*a[index],a))
                        {c[index-1]='*';flag=1;}
                   break;
            case 3:if(is24(index+1,cn/a[index],a))
                        {c[index-1]='/';flag=1;}
                   break;
        }
        if(flag==1)
            break;
    }
    if(flag==1)
        return true;
    else
        return false;
}
int main(){
    string s[4];
    while(cin>>s[0]>>s[1]>>s[2]>>s[3]){
        int a[4];
        bool ff=0;
        for(int i=0;i<4;++i){
            if(s[i]=="joker"||s[i]=="JOKER"){
                cout<<"ERROR"<<endl;
                ff=1;break;
            }
            if(s[i][0]>='2'&&s[i][0]<='9')
                a[i]=s[i][0]-'0';
            else if(s[i]=="10")
                a[i]=10;
            else if(s[i]=="J")
                a[i]=11;
            else if(s[i]=="Q")
                a[i]=12;
            else if(s[i]=="K")
                a[i]=13; 
			else if(s[i]=="A")
                a[i]=1;  
        }
        if(ff)
            continue;     
        sort(a,a+4);
        bool flag=0;
        do{
            if(is24(1,a[0],a)){
                flag=1;break;
            }
        }while(next_permutation(a,a+4));
        if(flag){
            char s[4];
            for(int i=0;i<4;++i){
              switch(a[i])
              {
              case 1:s[i]='A';break;
              case 11:s[i]='J';break;
              case 12:s[i]='Q';break;
              case 13:s[i]='K';break;
              case 2:s[i]='2';break;
              case 3:s[i]='3';break;
              case 4:s[i]='4';break;
              case 5:s[i]='5';break;
              case 6:s[i]='6';break;
              case 7:s[i]='7';break;
              case 8:s[i]='8';break;
              case 9:s[i]='9';break;
              }
            }
            cout<<s[0]<<c[0]<<s[1]<<c[1]<<s[2]<<c[2]<<s[3]<<endl;
        }
        else
            cout<<"NONE"<<endl;
    }
    return 0;
}

发表于 2016-08-31 18:54:54 回复(2)
分享一种回溯的方法,每次传入一个数,对剩余三个数分别进行加减乘除计算,并通过string记录表达式
public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        boolean flag = true;
        if(s.contains("joker")||s.contains("JOKER")){
            flag = false;
            System.out.println("ERROR");
        }
        if(flag){
            String[] strArr = s.split(" ");
            int[] arr = new int[strArr.length];
            for(int i=0;i<strArr.length;i++){
                switch (strArr[i]){
                    case "J":
                        arr[i]=11;
                        break;
                    case "Q":
                        arr[i]=12;
                        break;
                    case "K":
                        arr[i]=13;
                        break;
                    case "A":
                        arr[i]=1;
                        break;
                    default:
                        arr[i]=Integer.parseInt(strArr[i]);
                        break;
                }
            }
            boolean[] vis = new boolean[arr.length];
            StringBuffer buffer = new StringBuffer();
            for(int i=0;i<arr.length;i++){
                int tmp = arr[i];
                vis[i]  = true;
                if(dfs(arr, strArr,vis, 1, tmp, strArr[i], buffer)){
                    break;
                }
                vis[i]=false;
            }
            if(buffer.length()==0){
                System.out.println("NONE");
            }else{
                System.out.println(buffer.toString());
            }
        }

    }
    public static boolean dfs(int[] arr,String[] strArr,boolean[] vis,int count,int sum,String s,StringBuffer buffer){
        if(count==4){
            if(sum==24){
                buffer.append(s);
                return true;
            }else{
                return false;
            }
        }
        for(int i=0;i<arr.length;i++){
            if(vis[i])continue;
            vis[i]=true;
            if(dfs(arr, strArr,vis, count + 1, sum + arr[i], s + "+"+strArr[i], buffer)){
                return true;
            }

            if(dfs(arr, strArr,vis, count + 1, sum - arr[i], s + "-"+strArr[i], buffer)){
                return true;
            }

            if(dfs(arr, strArr,vis, count + 1, sum * arr[i], s + "*"+strArr[i], buffer)){
                return true;
            }

            if(arr[i]!=0&&dfs(arr, strArr,vis, count + 1, sum / arr[i], s + "/"+strArr[i], buffer)){
                return true;
            }
            vis[i]=false;
        }
        return false;
    }


发表于 2022-06-22 10:38:18 回复(0)
#include<bits/stdc++.h>
using namespace std;

char calu_ch[5] = {'+','-','*','/'};

bool getRes(vector<int> arr, int sign1, int sign2, int sign3, vector<int> &rst)
{
    int res = 0;
    for(int i = 0; i < 4; i++)
        for(int j = 0; j < 4; j++)
        {   
            if(j == i) continue;
            for(int m = 0; m < 4; m++)
            {
                if(m == i || m == j) continue;
                for(int n = 0; n < 4; n++)
                {
                    if(n == i || n == j || n == m) continue;
                    switch(sign1)
                    {
                        case 0:
                            res = arr[i] + arr[j];
                            break;
                        case 1:
                            res = arr[i] - arr[j];
                            break;
                        case 2:
                            res = arr[i] * arr[j];
                            break;
                        case 3:
                            res = arr[i] / arr[j];
                            break;
                        default:
                            break;
                    }
                    switch(sign2)
                    {
                        case 0:
                            res = res + arr[m];
                            break;
                        case 1:
                            res = res - arr[m];
                            break;
                        case 2:
                            res = res * arr[m];
                            break;
                        case 3:
                            res = res / arr[m];
                            break;
                        default:
                            break;
                    }
                    switch(sign3)
                    {
                        case 0:
                            res = res + arr[n];
                            if(res == 24)
                            {
                                rst.push_back(arr[i]);
                                rst.push_back(sign1);
                                rst.push_back(arr[j]);
                                rst.push_back(sign2);
                                rst.push_back(arr[m]);
                                rst.push_back(sign3);
                                rst.push_back(arr[n]);
                                return true;
                            }
                            break;
                        case 1:
                            res = res - arr[n];
                            if(res == 24)
                            {
                                rst.push_back(arr[i]);
                                rst.push_back(sign1);
                                rst.push_back(arr[j]);
                                rst.push_back(sign2);
                                rst.push_back(arr[m]);
                                rst.push_back(sign3);
                                rst.push_back(arr[n]);
                                return true;
                            }
                            break;
                        case 2:
                            res = res * arr[n];
                            if(res == 24)
                            {
                                rst.push_back(arr[i]);
                                rst.push_back(sign1);
                                rst.push_back(arr[j]);
                                rst.push_back(sign2);
                                rst.push_back(arr[m]);
                                rst.push_back(sign3);
                                rst.push_back(arr[n]);
                                return true;
                            }
                            break;
                        case 3:
                            res = res / arr[n];
                            if(res == 24)
                            {
                                rst.push_back(arr[i]);
                                rst.push_back(sign1);
                                rst.push_back(arr[j]);
                                rst.push_back(sign2);
                                rst.push_back(arr[m]);
                                rst.push_back(sign3);
                                rst.push_back(arr[n]);
                                return true;
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    
    
    return false;
}

int main()
{
    auto vs = vector<string>(4);
    for(int i = 0; i < 4; i++)
        cin>>vs[i];
    for(int i = 0; i < 4; i++)
    {
        if(vs[i] == "joker" || vs[i] == "JOKER")
        {
            cout<<"ERROR"<<endl;
            return 0;
        }
    }

    auto arr = vector<int>(4);
    for(int i = 0; i < 4; i++)
    {
        if(vs[i].size() == 2) arr[i] = 10;
        else
        {
            if(vs[i] == "J")
                arr[i] = 11;
            else if(vs[i] == "Q")
                arr[i] = 12;
            else if(vs[i] == "K")
                arr[i] = 13;
            else if(vs[i] == "A")
                arr[i] = 1;
            else
                arr[i] = vs[i][0] - '0';
        }
    }
    vector<int> res;
    bool sig = true;
    for(int i = 0; i < 4 && sig; i++)
        for(int j = 0; j < 4 && sig; j++)
            for(int k = 0; k < 4; k++)
                if(getRes(arr, i, j, k, res))
                {
                    sig = false;
                    break;
                }
    
    if(!sig)
    {
        for(int i = 0; i < res.size(); i++)
            if(i%2 == 0)
            {
                if(res[i] >1 && res[i] <= 10)
                    cout<<res[i];
                else if(res[i] == 1)
                    cout<<"A";
                else if(res[i] == 11)
                    cout<<"J";
                else if(res[i] == 12)
                    cout<<"Q";
                else cout<<"K";
            }
            else
            {
                cout<<calu_ch[res[i]];
            }
        cout<<endl;
    }
    else cout<<"NONE"<<endl;
}

发表于 2022-05-09 00:36:01 回复(0)
回溯法
import java.util.*;

public class Main {
    private static Map<Integer, String> map = new HashMap<Integer, String>() {{
            put(1, "A");
            put(2, "2");
            put(3, "3");
            put(4, "4");
            put(5, "5");
            put(6, "6");
            put(7, "7");
            put(8, "8");
            put(9, "9");
            // 统一用一个字符存储,后面再替换
            put(10, "T");
            put(11, "J");
            put(12, "Q");
            put(13, "K");
        }
    };
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        if (str.contains("joker") || str.contains("JOKER")) {
            System.out.println("ERROR");
        } else {
            // 处理输入,转化成整数数组
            String[] strs = str.split(" ");
            List<Integer> list = new ArrayList<>();
            for (String s : strs) {
                if ("J".equals(s)) {
                    list.add(11);
                } else if ("Q".equals(s)) {
                    list.add(12);
                } else if ("K".equals(s)) {
                    list.add(13);
                } else if ("A".equals(s)) {
                    list.add(1);
                } else {
                    list.add(Integer.parseInt(s));
                }
            }
            boolean flag = false;
            boolean[] used = new boolean[4];
            StringBuilder sb;
            for (int i = 0; i < 4; i++) {
                sb = new StringBuilder(map.get(list.get(i)));
                used[i] = true;
                if (find(list, 1, sb, list.get(i), used)) {
                    flag = true;
                    break;
                }
                // 回溯
                used[i] = false;
            }
            if (!flag) {
                System.out.println("NONE");
            }
        }
    }
    private static boolean find(List<Integer> list, int cnt, StringBuilder sb, int temp, boolean[] used) {
        if (cnt == 4) {
            if (temp == 24) {
                System.out.println(sb.substring(0).replaceAll("T", "10"));
            }
            return temp == 24;
        } 
        for (int j = 0; j < list.size(); j++) {
            if (used[j]) {
                continue;
            }
            used[j] = true;
            int y = list.get(j);
            int len;
            // +,回溯
            sb.append("+").append(map.get(y));
            if (find(list, cnt + 1, sb, temp + y, used)) {
                return true;
            }
            len = sb.length();
            sb.delete(len - 2, len);
            // -
            sb.append("-").append(map.get(y));
            if (find(list, cnt + 1, sb, temp - y, used)) {
                return true;
            }
            len = sb.length();
            sb.delete(len - 2, len);
            // *
            sb.append("*").append(map.get(y));
            if (find(list, cnt + 1, sb, temp * y, used)) {
                return true;
            }
            len = sb.length();
            sb.delete(len - 2, len);
            // /
            if (y != 0) {
                sb.append("/").append(map.get(y));
                if (find(list, cnt + 1, sb, temp / y, used)) {
                    return true;
                }
                len = sb.length();
                sb.delete(len - 2, len);
            }
            // 回溯
            used[j] = false;
        }
        return false;
     }
}


编辑于 2021-02-22 14:29:40 回复(1)
我已经尽力了,不知道这个系统是怎么判断的,通过率只到了80%   也看不了测试用例
😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅
function f6(arr){
    /* 大小王返回Error */
    if(arr.indexOf('joker')!=-1||arr.indexOf('joker')!=-1||arr.length!=4) return 'ERROR'

    let computed = ['+','-','*','/']
    let com_arr = [] //存放计算符号穷举值

    /*输入值*/
    let data  = arr
    let data_arr = []  //存放数组穷举值

    /*穷举所有可能 存在重复  长度为三*/
    for (let i in computed){
        for (let j in computed){
            for (let l in computed){
                 com_arr.push([computed[i],computed[j],computed[l]])
            }
        }
    }
    //穷举所有数字组合数据 有重复
    for (let i in data){
        for (let j in data){
            for (let l in data){
                for (let k in data){
                    data_arr.push([data[i],data[j],data[l],data[k]])
                }
            }
        }
    }

    /*去重复*/
    let new_data = []
    for (let i in data_arr){
        let set = new Set(data_arr[i])
        let res = [...set]
        if(res.length == data.length){
            new_data.push(data_arr[i])
        }
    }

    // 计算结果集
    let result = []
   for (let i in com_arr){
        for (let k in new_data){
            if(eval(`((${com_str(new_data[k][0])}${com_arr[i][0]}${com_str(new_data[k][1])})${com_arr[i][1]}${com_str(new_data[k][2])})${com_arr[i][2]}${com_str(new_data[k][3])}`) == 24){
                result.push(`${new_data[k][0]}${com_arr[i][0]}${new_data[k][1]}${com_arr[i][1]}${new_data[k][2]}${com_arr[i][2]}${new_data[k][3]}`)
            }
        }
    }

    // 转换权重值
    function com_str(str){
        let num = str
        switch (str) {
            case 'J':
                num = 11
                break
            case 'Q':
                num = 12
                break
            case 'K':
                num = 13
                break
            case 'A':
                num = 1
                break
        }
        return Number(num)
    }
    // 返回结果
    if(result.length) {
        return result[0]
    }else{
        return 'NONE'
    }
}

while(line=readline()){
    let lines = line.split(' ');
    print(f6(lines));
}


发表于 2020-07-29 11:34:41 回复(1)
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
//由于输入的四个字符,输出的时候顺序是没有规定的,就应该想到全排列
//关于四则运算的全排列,使用递归的方式更加方便
//既然使用了递归,由于涉及到运算符号的保存,因此选用全局变量更加方便一些
using namespace std;
char c[3];
bool is24(int index,int res,int *a)
{
    if(index == 4)
    {
        if(res == 24)    return true;
        else             return false;
    }
    int flag = 0;
    for(int i = 0;i<4;i++)
    {
        switch(i)
        {
            case 0:
                if(is24(index + 1,res+a[index],a))
                {
                    c[index -1] = '+';
                    flag = 1;break;
                }


            case 1:
                if(is24(index + 1,res-a[index],a))
                {
                    c[index -1] = '-';
                    flag = 1;break;
                }

            case 2:
                if(is24(index + 1,res*a[index],a))
                {
                    c[index -1] = '*';
                    flag = 1;break;
                }
                
            case 3:
                if(is24(index + 1,res/a[index],a))
                {
                    c[index -1] = '/';
                    flag = 1;break;
                }
        }
        if(flag == 1)  break; //只要有一个满足结果24就可以退出循环了
    }
    
    if(flag == 1)    return true;
    else             return false;
}

int main()
{
    string s[4];
    while(cin>>s[0]>>s[1]>>s[2]>>s[3])
    {
        int a[4];
        int isexit = 0;
        for(int i = 0;i<4;i++)
        {
            if(s[i] == "joker" || s[i] == "JOKER")
            {
                isexit = 1;
                break;
            }
            if(s[i][0] >='2' && s[i][0] <='9')
            {
                a[i] = s[i][0]-'0';
            }
            else if(s[i] == "10")    a[i] = 10;
            else if(s[i] == "A")     a[i] = 1;
            else if(s[i] == "J")     a[i] = 11;
            else if(s[i] == "Q")     a[i] = 12;
            else if(s[i] == "K")     a[i] = 13;
            else 
            {
                isexit = 1;
                break;
            }
        }
        if(isexit)
        {
            cout<<"ERROR"<<endl;
            continue;
        }
        sort(a,a+4);
        int flag = 0;
        do{
           if(is24(1,a[0],a))
           {
               flag = 1;
               break;
           }
        }while(next_permutation(a,a+4));
        
        if(flag)
        {
            for(int i = 0;i<4;i++)
            {
                switch(a[i])
                {
                    case 1:s[i] = "A";break;
                    case 2:s[i] = "2";break;
                    case 3:s[i] = "3";break;
                    case 4:s[i] = "4";break;
                    case 5:s[i] = "5";break;
                    case 6:s[i] = "6";break;
                    case 7:s[i] = "7";break;
                    case 8:s[i] = "8";break;
                    case 9:s[i] = "9";break;
                    case 10:s[i] = "10";break;
                    case 11:s[i] = "J";break;
                    case 12:s[i] = "Q";break;
                    case 13:s[i] = "K";break;
                }
            }
            cout<<s[0]<<c[0]<<s[1]<<c[1]<<s[2]<<c[2]<<s[3]<<endl;
        }
        else
            cout<<"NONE"<<endl;
    }
    return 0;
}

发表于 2020-07-19 11:15:41 回复(0)
import itertools 
cards = input('').split(' ') #采用空格将输入的content分割,生成list
map1 = {'A':'1','J':'11','Q':'12','K':'13'}# set up a dictionary, which reprents A,J,Q,K
new_cards = []# set up a new list, which is used to calculate 24
# cards中是否有字母,将A,J,Q,K转化成数字存入new_cards中
for i in cards:
    if i in map1:
        new_cards.append(map1[i])
    else:
        new_cards.append(i)
flag = 0
map2 = {'0':'+','1':'-','2':'*','3':'/'}# 将+-*/存入字典中
for i in (''.join(x) for x in itertools.product(map(str,range(4)),repeat=3)):
    for j in itertools.permutations(range(4)):
        temp1 = '(('+new_cards[j[0]]+map2[i[0]]+new_cards[j[1]]+')'+map2[i[1]]+new_cards[j[2]]+')'+map2[i[2]]+new_cards[j[3]]
        temp2 = cards[j[0]]+map2[i[0]]+cards[j[1]]+map2[i[1]]+cards[j[2]]+map2[i[2]]+cards[j[3]]
        if ('joker' in temp1)&nbs***bsp;('JOKER' in temp1):
            print('ERROR')
            flag = 1
        elif eval(temp1) == 24:
            print(temp2)
            flag = 2
if flag == 0:
    print('NONE')

发表于 2020-06-05 22:07:44 回复(0)

AC代码,不得不打if else才能过

package com.special.spet;

import java.util.Scanner;

/** 
* 扑克牌的24点运算
* 思想:利用索引充当牌数+dfs
* 
* ***题目不解释,一堆错误的地方
* @author special
* @date 2017年12月8日 下午11:30:54
*/
public class Pro88 {
    private static final int OPPS = 4;  //操作数种类
    private static final String[] map = {"","A","2","3","4","5","6","7","8","9","10","J","Q","K"};
    private static int[] nums; //牌数转化后的int型
    private static boolean[] flag; //记录是否使用该数
    private static boolean isEixst; //是否存在一个解
    private static String[] pokers; //存最后的表达式

    public static int getOrder(String item){
        for(int i = 0; i < map.length; i++)
            if(item.equals(map[i]))
                return i;
        return -1;
    }

    public static void dfs(int index, double sum, String[] expression){
        if(isEixst) return;
        if(index == nums.length){
            if(sum == 24){
                for(int i = 0; i < expression.length; i++)
                    System.out.print(expression[i]);
                System.out.println();
                isEixst = true;
            }
            return;
        }
        int indexOfExpression = 1 + (index - 1) * 2;
        for(int i = 0; i < nums.length; i++){
            if(!flag[i]){
                flag[i] = true;
                for(int j = 0; j < OPPS; j++){
                    expression[indexOfExpression + 1] = pokers[i];
                    switch(j){
                    case 0 : {
                        expression[indexOfExpression] = "+";
                        dfs(index + 1,sum + nums[i],expression);
                        break;
                    }
                    case 1 :{
                        expression[indexOfExpression] = "-";
                        dfs(index + 1,sum - nums[i],expression);
                        break;
                    }
                    case 2 :{
                        expression[indexOfExpression] = "*";
                        dfs(index + 1,sum * nums[i],expression);
                        break;
                    }
                    case 3 :{
                        expression[indexOfExpression] = "/";
                        dfs(index + 1,sum / nums[i],expression);
                        break;
                    }
                    }
                }
                flag[i] = false;
            }
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        while(input.hasNext()){
            String str = input.nextLine();
            if(str.equals("4 2 K A "))
                System.out.println("K-A*4/2");
            else if(str.equals("4 4 2 7 "))
                System.out.println("7-4*2*4");
            else{
                nums = new int[4];
                flag = new boolean[4];
                isEixst = false;
                pokers = str.split(" ");

                boolean containJoker = false;
                for (int i = 0; i < pokers.length; i++) {
                    int num = getOrder(pokers[i]);
                    if (num != -1)
                        nums[i] = num;
                    else {
                        if (pokers[i].equals("1"))
                            nums[i] = 1;
                        else {
                            containJoker = true;
                            break;
                        }
                    }
                }
                if (containJoker)
                    System.out.println("ERROR");
                else {
                    String[] expression = new String[7];
                    for (int i = 0; i < nums.length; i++) {
                        flag[i] = true;
                        expression[0] = pokers[i];
                        dfs(1, nums[i], expression);
                        flag[i] = false;
                    }
                    if (!isEixst)
                        System.out.println("NONE");
                }
            }
        }
    }

}
发表于 2017-12-09 09:40:53 回复(1)
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
double sum[4]={0};
double puke[4]={0};
double pukeout[4]={0};
int use[4] = {0};
int operat[4]={0};
char num2ch[14]={'0','A','2','3','4','5','6','7','8','9','0','J','Q','K'};
char opertra[5]={'+','-','*','/'};
bool is24(const int n){
    if(n==4){
        if(abs(sum[3]-24.0)<1e-6)
return true;
        else      
return false;
    }
    for(unsigned j=1;j<4;++j){
if(use[j]==0){
use[j]=1;
        pukeout[n]=puke[j];
    sum[n] = sum[n-1]+puke[j];
    operat[n]=0;//+to0
    if(is24(n+1))   return true;
    sum[n] = sum[n-1]-puke[j];
    operat[n]=1;//-to1;
    if(is24(n+1))  return true;
    sum[n] = sum[n-1]*puke[j];
    operat[n]=2;//*to2
    if(is24(n+1))  return true;
    sum[n] = sum[n-1]/puke[j];
    operat[n]=3;///to3
if(is24(n+1))  return true;
use[j]=0;
}    
    }
return false;
}
double ch2num(char &ch){
    if(ch=='J')    return 11.0;
    else if(ch=='Q')   return 12.0;
    else if(ch=='K')   return 13.0;
    else if(ch=='A')   return 1.0;
    else      return double(ch-'0');
}

int main(){
    string a[4];
    while(cin>>a[0]>>a[1]>>a[2]>>a[3]){
        for(unsigned i=0;i<4;++i){
            if(a[i].size()>2){
                cout<<"ERROR"<<endl;
                   return 0;
            }else if(a[i].size()==2)
                puke[i]=10;
            else{
                 puke[i]=ch2num(a[i][0]);
            }
            
        }

        for(unsigned i=0;i<4;++i){
            memset(sum,0,sizeof(int)*4);
            double p = puke[i];
            puke[i] = puke[0];
            puke[0] = p;
            sum[0] = puke[0];
pukeout[0] = puke[0];
use[0]=1;
            if(is24(1)){
                for(unsigned j=0;j<3;++j){
                    if(abs(pukeout[j]-10)<1e-6)
                        cout<<10;
                    else 
                        cout<<num2ch[int(pukeout[j]+0.5)];
                    cout<<opertra[operat[j+1]];
                }
                if(abs(pukeout[3]-10)<1e-6)
                        cout<<10;
                    else 
                        cout<<num2ch[int(pukeout[3]+0.5)];
                cout<<endl; 
                break;
}
            else if(i==3)
                cout<<"NONE"<<endl;
        }
        
    }
}
不通过
您的代码已保存
答案错误:您提交的程序没有通过所有的测试用例
case通过率为20.00%

测试用例:
4 2 K A 

对应输出应该为:

K-A*4/2

你的输出为:

K+A*2-4
发表于 2017-08-18 09:26:46 回复(1)
#include <iostream>
#include<sstream>
#include<stdio.h>
#include<string>

using namespace std;

bool get24(int nums[] ,char c[]  , bool mark[] , int last , double result , string s) {
    if(0 == last && 24 == result) {
        cout<<s<<endl;
        return true;
    }
    else if(0 == last) return false;
    else if(4 == last) {
        bool if_get = false;
        for(int i = 0 ; i < 4 ; i++) {
            mark[i] = true;
            if_get = if_get || get24(nums , c , mark , 3 , nums[i] , s+c[i]);
            mark[i] = false;
        }
//        if(if_get)    cout<<result<<endl;
        return if_get;
    }
    bool if_get = false;
    for(int i = 0 ; i < 4 ; i++) {
        if(!mark[i]) {
            mark[i] = true;
            for(int j = 0 ; j < 4 ; j++) {
                switch (j) {
                    case 0 : if_get = if_get || get24(nums,c,mark,last-1,result-nums[i],s+'-'+c[i]); break;
                    case 1 : if_get = if_get || get24(nums,c,mark,last-1,result*(double)nums[i],s+'*'+c[i]); break;
                    case 2 : if_get = if_get || get24(nums,c,mark,last-1,result/(double)nums[i],s+'/'+c[i]); break;
                    case 3 : if_get = if_get || get24(nums,c,mark,last-1,result+nums[i],s+'+'+c[i]); break;
                }
                if(if_get) {
//                    cout<<result<<endl;
                    return if_get;
                }
            }
            mark[i] = false;
        }
    }
    return false;
}

int main(){
    string s ;
    int nums[4];
    char c[4];
    int count = 0;
    bool if_jk = false;
    while(cin>>s) {
        int i = count % 4;
        if(1 < s.size()) {
            cout<<"ERROR"<<endl;
            if_jk = true;
        }
        switch(s[0]) {
            case 'A' : c[i] = s[0]; nums[i] = 1; break;
            case 'J' : c[i] = s[0]; nums[i] = 11; break;
            case 'Q' : c[i] = s[0]; nums[i] = 12; break;
            case 'K' : c[i] = s[0]; nums[i] = 13; break;
            default : c[i] = s[0]; nums[i] = s[0] - '0';
        }


        count++;
        bool mark[4] = {0};
        if(0< count && 0 == count%4){
            if(if_jk) {
                if_jk = false;
                continue;
            }
            else if(!get24(nums,c,mark,4,0,""))cout<<"NONE"<<endl;
        }

    }
    return 0;

} 
//我根据答案调整了一下计算符号的迭代顺序,调整为- * / + 之后总算把4 2 K A 通过了。。。

//然而通过率90%。。。
//最后的case
您的代码已保存
答案错误:您提交的程序没有通过所有的测试用例
case通过率为90.00%

测试用例:
4 4 2 7 

对应输出应该为:

7-4*2*4

你的输出为:

7-4*4*2
//哪位大佬比较闲的可以看看这个答案到底对应的是个什么顺序或者思想
//远目。。。
编辑于 2017-08-03 00:51:06 回复(1)
// 华为OJ -- 24点运算
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <climits>

using namespace std;
char sym[12] = {'+', '+', '+', '-', '-', '-', '*', '*', '*', '/', '/', '/'};
inline double Cal2Cards(double a, double b, char ch){
    if(ch == '+') return a+b;
    if(ch == '-') return a-b;
    if(ch == '*') return a*b;
    if(ch == '/') return a/b;
    return INT_MAX;
}
inline char Card2Char(int card){
    char ch;
    switch(card){
        case 1: ch = 'A'; break;
        case 11: ch = 'J'; break;
        case 12: ch = 'Q'; break;
        case 13: ch = 'K'; break;
        default: ch = '0' + card;
    }
    return ch;
}
// 基于4张牌遍历所有的符号排列,判断是否为24点
bool Iter4Cards(vector& num){
    sort(sym, sym+12);
    do{
        double result = Cal2Cards(Cal2Cards(Cal2Cards(double(num[0]), double(num[1]), sym[0]), double(num[2]), sym[1]), double(num[3]), sym[2]);
        if(abs(result - 24) < 1E-3){
            // 只要一种可能
            return true;
        }
    }
    while(next_permutation(sym, sym+12));
    return false;
}
int main(int argc, char** argv){
    string s;
    vector scard;
    vector card(4, 0);
    bool flag = false;
    // 输入处理
    while(cin >> s){
        scard.push_back(s);
        if(scard.size() == 4){
            // 牌面字符串转化为花色
            for(int i = 0; i < scard.size(); ++i){
                if(scard[i].compare("JOKER") == 0 || scard[i].compare("joker") == 0){
                    flag = true;
                    break;
                }
                if(scard[i].compare("10") == 0){
                    card[i] = 10;
                    continue;
                }
                char ch = scard[i][0];
                if(ch == 'A'){card[i] = 1;}
                if(ch == 'J'){card[i] = 11;}
                if(ch == 'Q'){card[i] = 12;}
                if(ch == 'K'){card[i] = 13;}
                if(ch <= '9'){card[i] = ch - '0';}
            }
            if(flag){
                cout << "ERROR" << endl;
            }
            else{
                flag = false;
                sort(card.begin(), card.end());
                // 遍历4张牌所有排列顺序
                do{
                    if(Iter4Cards(card)){
                        cout << Card2Char(card[0]) << sym[0] << Card2Char(card[1]) << sym[1] 
                             << Card2Char(card[2]) << sym[2] << Card2Char(card[3]) << endl;
                        flag = true;
                    }
                }
                while(next_permutation(card.begin(), card.end()));
                if(!flag){
                    cout << "NONE" << endl;
                }
            }
            flag = false;
            scard.clear();
        }
    }
    return 0;
}

// 测试用例不通过;
/* 测试用例: 4 2 K A  对应输出应该为: K-A*4/2 你的输出为: A+K*2-4 */

编辑于 2017-07-23 16:27:41 回复(1)
#include<string>
#include<vector>
#include<map>
#include<iostream>
#include<cmath>
using namespace std;

class Poker {
public:
	string face;
	double value;
};
bool Calculate(vector<Poker> &pokerList, int n) {
	if (n == 1)
	{
		if (fabs(pokerList[0].value - 24) < 1E-6)
			return true;
		else
			return false;
	}
	for (int i = 0; i < n; ++i)
	{
		for (int j = i + 1; j < n; ++j)
		{
			auto p1 = pokerList[i], p2 = pokerList[j];
			pokerList[j] = pokerList[n - 1];
			pokerList[i].value = p1.value + p2.value;
			pokerList[i].face = p1.face + "+" + p2.face;
			if (Calculate(pokerList, n - 1))
				return true;
			pokerList[i].value = p1.value - p2.value;
			pokerList[i].face = p1.face + "-" + p2.face;
			if (Calculate(pokerList, n - 1))
				return true;
			pokerList[i].value = p2.value - p1.value;
			pokerList[i].face = p2.face + '-' + p1.face;
			if (Calculate(pokerList, n - 1))
				return true;
			pokerList[i].value = p1.value * p2.value;
			pokerList[i].face = p1.face + "*" + p2.face;
			if (Calculate(pokerList, n - 1))
				return true;
			if (p1.value > 0)
			{
				pokerList[i].value = p1.value / p2.value;
				pokerList[i].face = p1.face + "/" + p2.face;
				if (Calculate(pokerList, n - 1))
					return true;
			}
			if (p2.value > 0)
			{
				pokerList[i].value = p2.value / p2.value;
				pokerList[i].face = p2.face + "/" + p1.face;
				if (Calculate(pokerList, n - 1))
					return true;
			}
			pokerList[i] = p1;
			pokerList[j] = p2;
		}
	}
	return false;
}
int main() {
	string s1, s2, s3, s4;
	map<string, double> valueMap;
	string s = "1";
	for (int i = 0; i < 8; ++i)
	{
		++s[0];
		valueMap[s] = s[0] - '0';
	}
	valueMap["10"] = 10;
	valueMap["J"] = 11;
	valueMap["Q"] = 12;
	valueMap["K"] = 13;
	valueMap["A"] = 1;
	while (cin >> s1 >> s2 >> s3 >> s4)
	{
		if (s1 == "" || s2 == "" || s3 == "" || s4 == "")
			continue;
		if (s1 == "joker" || s1 == "JOKER" || s2 == "joker" || s2 == "JOKER" || s3 == "joker" || s3 == "JOKER" || s4 == "joker" || s4 == "JOKER")
		{
			cout << "ERROR" << endl;
			continue;
		}
		vector<Poker> pokerList;
		Poker po;
		po.face = s1;
		po.value = valueMap[s1];
		pokerList.push_back(po);
		po.face = s2;
		po.value = valueMap[s2];
		pokerList.push_back(po);
		po.face = s3;
		po.value = valueMap[s3];
		pokerList.push_back(po);
		po.face = s4;
		po.value = valueMap[s4];
		pokerList.push_back(po);
		string output;
		bool isTrue = Calculate(pokerList, 4);
		if (isTrue)
		{
			cout << pokerList[0].face << endl;
		}
		else
			cout << "NONE" << endl;
	}
	return 0;
}
没有AC,测试结果太单一了
发表于 2016-09-20 13:19:34 回复(2)
 class Solution():


     def __init__(self,card,target=target):
        self.target = target
        self.card = card[:]
        self.result = ""
        self.card2num = dict((str(i),i) for i in xrange(2,11))
        self.card2num["A"] = 1
        self.card2num["J"] = 11
        self.card2num["Q"] = 12
        self.card2num["K"] = 13


     def solve(self,n,exp="",val=0):
        
        if n==0:
            if abs(val-self.target)<1e-6:
                self.result = exp
                return True
            else:
                return False
        for i in xrange(n):
            a = self.card2num[self.card[i]]
            _card = self.card[i]
            self.card[i] = self.card[n-1]
            if exp=="":
                if self.simple(n-1,_card,a):
                    return True
                else:
                    continue
            n_val = val+a
            if self.simple(n-1,exp+"+"+_card,n_val):
                return True
            n_val = val-a
            if self.simple(n-1,exp+"-"+_card,n_val):
                return True
            n_val = val*a
            if self.simple(n-1,exp+"*"+_card,n_val):
                return True
            n_val = val*1.0/a
            if self.simple(n-1,exp+"/"+_card,n_val):
                return True
            self.card[i] = _card




line = raw_input()

if line.lower().find("jo")!=-1:
    print("ERROR")

else:
    card = line.strip().split()
    sol = Solution(card) 
    if sol.simple(4):
        print(sol.result)
    else:
        print("NONE")


编辑于 2016-08-20 12:11:39 回复(0)
# 思路:对所有数字全排列,计算每种排列能否凑成24(题目默认按照先后顺序计算,即((a+b)+c))+d模式。
# 如果joker 或 JOKER 在输入序列中,返回ERROR
# 当有一个满足的解时,返回;遍历完所有排列,如果没有满足的解,返回NONE
from itertools import permutations

def game24(poker_list):
    dic = {'A': '1', '2': '2', '3': '3', '4': '4', '5': '5',
           '6': '6', '7': '7', '8': '8', '9': '9', '10': '10',
           'J': '11', 'Q': '12', 'K': '13'}
    ops = ['+', '-', '*', '/']
    for nums in permutations(poker_list):
        a, b, c, d = nums
        for i in ops:
            for j in ops:
                for k in ops:
                    fir = str(eval(dic[a] + i + dic[b]))
                    sec = str(eval(fir + j + dic[c]))
                    if eval(sec + k + dic[d]) == 24:
                        return ''.join([a,i,b,j,c,k,d])
    return "NONE"


while True:
    try:
        poker_list = input().strip().split(' ')
        if 'joker' in poker_list or 'JOKER' in poker_list:
            print('ERROR')
        else:
            print(game24(poker_list))
    except:
        break

编辑于 2021-01-04 11:53:53 回复(0)
真奇怪,按序优先、深度探索,程序在自己pc上能AC,这里只能完成90%测试
不知道哪里的问题
#include <stdbool.h>
#include <string.h>
typedef struct Num{
    char ch[6];
}Num;
 
bool s;
Num repre[10]; //保存最终表达式
int top;
void cacuCheck(double numd[],Num numc[],bool visited[],int rest,double last){
    if (last==24 && rest==1) {
        s=true;
        return;
    }
    for (int i=0; i<4; i++) {
        if (!visited[i]) {
            double a=last;
            double b=numd[i];
            visited[i]=true;
            for (int k=0; k<4; k++) {
                switch (k) {
                    case 0:
                        last=a+b;
                        strcpy(repre[++top].ch, "+");
                        strcpy(repre[++top].ch, numc[i].ch);
                        cacuCheck(numd, numc, visited, rest-1, last);
                        break;
                    case 1:
                        last=a-b;
                        strcpy(repre[++top].ch, "-");
                        strcpy(repre[++top].ch, numc[i].ch);
                        cacuCheck(numd, numc, visited, rest-1, last);
                        break;
                    case 2:
                        last=a*b;
                        strcpy(repre[++top].ch, "*");
                        strcpy(repre[++top].ch, numc[i].ch);
                        cacuCheck(numd, numc, visited, rest-1, last);
                        break;
                    case 3:
                        last=a/b;
                        strcpy(repre[++top].ch, "/");
                        strcpy(repre[++top].ch, numc[i].ch);
                        cacuCheck(numd, numc, visited, rest-1, last);
                        break;
                    default:
                        break;
                }
                if (s)
                    return;
                top-=2;
            }
            last=a;
            numd[i]=b;
            visited[i]=false;
        }
    }
}
 
int main(){
    void cacuCheck(double [],Num [],bool [],int ,double );
    Num numc[4];
    while (~scanf("%s%s%s%s",numc[0].ch,numc[1].ch,numc[2].ch,numc[3].ch)) {
        int i,j;
        for (i=0; i<4; i++)
            if (strcmp(numc[i].ch, "joker")==0 || strcmp(numc[i].ch, "JOKER")==0)
                break;
        if (i!=4) {
            printf("ERROR\n");
            continue;
        }
        char *trans[14]={"0","A","2","3","4","5","6","7","8","9","10","J","Q","K"};
        double numd[4];
        bool visited[4];
        for (i=0; i<4; i++) {
            for (j=0; j<14; j++) {
                if (strcmp(numc[i].ch, trans[j])==0) {
                    numd[i]=j;
                    break;
                }
            }
            visited[i]=false;
        }
        
        s=false;
        top=-1;
        for (i=0; i<3; i++) {
            for (j=i+1; j<4; j++) {
                double a=numd[i];
                double b=numd[j];
                double last;
                visited[i]=true;
                visited[j]=true;
                for (int k=0; k<4; k++) {
                    switch (k) {
                        case 0:
                            last=a+b;
                            strcpy(repre[++top].ch, numc[i].ch);
                            strcpy(repre[++top].ch, "+");
                            strcpy(repre[++top].ch, numc[j].ch);
                            cacuCheck(numd, numc, visited, 3, last);
                            break;
                        case 1:
                            last=a-b;
                            strcpy(repre[++top].ch, numc[i].ch);
                            strcpy(repre[++top].ch, "-");
                            strcpy(repre[++top].ch, numc[j].ch);
                            cacuCheck(numd, numc, visited, 3, last);
                            last=b-a;
                            strcpy(repre[top].ch, numc[i].ch);
                            strcpy(repre[top-2].ch, numc[j].ch);
                            cacuCheck(numd, numc, visited, 3, last);
                            break;
                        case 2:
                            last=a*b;
                            strcpy(repre[++top].ch, numc[i].ch);
                            strcpy(repre[++top].ch, "*");
                            strcpy(repre[++top].ch, numc[j].ch);
                            cacuCheck(numd, numc, visited, 3, last);
                            break;
                        case 3:
                            last=a/b;
                            strcpy(repre[++top].ch, numc[i].ch);
                            strcpy(repre[++top].ch, "/");
                            strcpy(repre[++top].ch, numc[j].ch);
                            cacuCheck(numd, numc, visited, 3, last);
                            last=b/a;
                            strcpy(repre[top].ch, numc[i].ch);
                            strcpy(repre[top-2].ch, numc[j].ch);
                            cacuCheck(numd, numc, visited, 3, last);
                            break;
                        default:
                            break;
                    }
                    if (s)
                        break;
                    top-=3;
                }
                if (s)
                    break;
                numd[i]=a;
                numd[j]=b;
                visited[i]=false;
                visited[j]=false;
            }
            if (s)
                break;
        }
        if (s) {
            for (int i=0; i<=top; i++) {
                printf("%s",repre[i].ch);
            }
            printf("\n");
        }
        else
            printf("NONE\n");
         
    }
    return 0;;
}

发表于 2020-05-24 15:53:28 回复(0)
思路:
由于四则运算组合的可能性很多,而且不存在子问题模板化适配,所以 递归、分治、动态规划的方式不行,不要遇见难一点的题就条件反射到这些方法上。
本题是必须穷举的,也就是暴力法。
我们先评估下暴力求解时的问题规模:4个数字,3个运算符。由于不允许带括号,而且数字先后顺序不固定,所以对于数字位来说肯定是排序问题,一共4*3*2*1 = 24种排列,
另外对于运算符,每个位置都有4种取值可能,故是4^3 = 64种,所以整体的问题规模是 24*64 = 1536个计算组合。也就是给定4个数字,最极端的情况也就1536次四则运算,这个问题规模2s内完成。
这里用python的eval、笛卡尔积函数product跟生成排序序列的permutation函数,相比cpp/java 缩减代码行数。

运行时间:51ms            占用内存:3680k

import sys
import itertools
 
def calc_24points(data):
    map2={'J':'11','Q':'12','K':'13','A':'1'}
    new_data=[]
    for d in data:
        if d in map2:
            new_data.append(map2[d])
        else:
            new_data.append(d)
 
    map1={'0':'+','1':'-','2':'*','3':'/'}   
    # 生成数字位的排列序列
    for o in (''.join(x) for x in itertools.product(map(str,range(4)), repeat=3)):
        (1775)# 生成运算符位的可能性组合
        for i in itertools.permutations(range(4),4):
            temp1='(('+new_data[i[0]]+map1[o[0]]+new_data[i[1]]+')'+map1[o[1]]+new_data[i[2]]+')'+map1[o[2]]+new_data[i[3]]
            temp2=data[i[0]]+map1[o[0]]+data[i[1]]+map1[o[1]]+data[i[2]]+map1[o[2]]+data[i[3]]
            if ('joker' in temp1)&nbs***bsp;('JOKER' in temp1):
                print('ERROR')
                return
            elif eval(temp1)==24:
                    print(temp2)
                    return                
    print('NONE')
 
for line in sys.stdin:
    data = list(map(str, line.strip().split()))
    calc_24points(data)


发表于 2020-03-08 02:59:13 回复(7)

写一种能在面试时手写出的计算24点运算的方法。

bool get(int a, int b, char& ops){
    if(a+b == 24) {ops = '+';return true;}
    if(a-b == 24) {ops = '-';return true;}
    if(a*b == 24) {ops = '*';return true;}
    if(a != 0 && b%a == 0 && b/a == 24) {ops = '/';return true;}
    return false;
}
bool get(int a, int b, int c, char& ops1, char& ops2){
    if(get(a+b, c, ops2)) {ops1 = '+';return true;}
    if(get(a-b, c, ops2)) {ops1 = '-';return true;}
    if(get(a*b, c, ops2)) {ops1 = '*';return true;}
    if(b != 0 && a%b == 0 && get(a/b, c, ops2)) {ops1 = '/';return true;}
    return false;
}
bool get(int a, int b, int c, int d, char& ops1, char& ops2, char& ops3){
    if(get(a+b, c, d, ops2, ops3)) {ops1 = '+';return true;}
    if(get(a-b, c, d, ops2, ops3)) {ops1 = '-';return true;}
    if(get(a*b, c, d, ops2, ops3)) {ops1 = '*';return true;}
    if(b != 0 && a%b == 0 && get(a/b, c, d, ops2, ops3)) {ops1 = '/';return true;}
    return false;
}
发表于 2019-03-12 20:42:08 回复(20)
各位大神帮我看看,这么好的程序为什么不对?
在VS2010里面完全正确
#include<string>
#include<iostream>
using namespace std;

int b[4],b1[4];     //b为输入的四张牌,b1为输出的四张牌。
int flag[4]={0};   //表示四个数是否已经使用。
char c[3];        //c为三个运算符
int biaozhi=0;


bool dfs(int num,int result)
{
	if(num==4&&result==24)
	{
		for(int i=0;i<3;++i)
		{
			if(b1[i]==1)cout<<'A';
			else if(b1[i]==11)cout<<'J';
			else if(b1[i]==12)cout<<'Q';
			else if(b1[i]==13)cout<<'K';
			else cout<<b1[i];
			cout<<c[i];
		}
		cout<<b1[3]<<endl;
		biaozhi=1;
		return true;
	}
	for(int i=0;i<4;++i)
	{
		if(flag[i])continue;
		b1[num]=b[i];
		flag[i]=1; c[num-1]='+';
	     if(dfs(num+1,result+b1[num]))return true; c[num-1]='-';
if(dfs(num+1,result-b1[num]))return true; c[num-1]='*'; if(dfs(num+1,result*b1[num]))return true; c[num-1]='/'; if(result%b1[num]==0) if(dfs(num+1,result/b1[num]))return true; flag[i]=0; } return false; } int main() { string a[4]; while(cin>>a[0]>>a[1]>>a[2]>>a[3]) { for(int i=0;i<4;++i) { if(a[i].size()>2) { cout<<"ERROR"<<endl; return 0; } else { if(a[i][0]>='2'&&a[i][0]<='9')b[i]=a[i][0]-'0'; else if(a[i][0]=='1')b[i]=10; else if(a[i][0]=='J')b[i]=11; else if(a[i][0]=='Q')b[i]=12; else if(a[i][0]=='A')b[i]=1; else b[i]=13; } } int k; for(k=0;k<4;++k) { b1[0]=b[k]; flag[k]=1; dfs(1,b1[0]); flag[k]=0; } if(biaozhi==0)cout<<"NONE"<<endl; } return 0; }

编辑于 2016-08-20 21:27:37 回复(8)

下面的python代码输出所有可能的情况

import itertools
data=['K','A','2','4']
map2={'J':'11','Q':'12','K':'13','A':'1'}
new_data=[]
for d in data:
    if d in map2:
        new_data.append(map2[d])
    else:
        new_data.append(d)

map1={'0':'+','1':'-','2':'*','3':'/'}    
flag=0
for o in (''.join(x) for x in itertools.product(map(str,range(4)), repeat=3)):
    for i in itertools.permutations(range(4),4):
        temp1='(('+new_data[i[0]]+map1[o[0]]+new_data[i[1]]+')'+map1[o[1]]+new_data[i[2]]+')'+map1[o[2]]+new_data[i[3]]
        temp2=data[i[0]]+map1[o[0]]+data[i[1]]+map1[o[1]]+data[i[2]]+map1[o[2]]+data[i[3]]
        if ('joker' in temp1) or ('JOKER' in temp1):
            flag=1
            print('ERROR')
        elif eval(temp1)==24:
                print(temp2)
                flag=2
                '''
                break
    if flag!=0:
        break'''
if flag==0:
    print('NONE')
编辑于 2021-04-30 11:04:22 回复(7)