java用撲克牌計算24點
阿新 • • 發佈:2020-03-07
一副撲克牌的每張牌表示一個數(J、Q、K 分別表示 11、12、13,兩個司令都表示 6)。任取4 張牌,即得到 4 個 1~13 的數,請新增運算子(規定為加+ 減- 乘* 除/ 四種)使之成為一個運算式。每個數只能參與一次運算,4 個數順序可以任意組合,4 個運算子任意取 3 個且可以重複取。運算遵從一定優先級別,可加括號控制,最終使運算結果為 24。請輸出一種解決方案的表示式,用括號表示運算優先。如果沒有一種解決方案,則輸出 -1 表示無解。
輸入格式:
輸入在一行中給出 4 個整數,每個整數取值在 [1,13]。
輸出格式:
輸出任一種解決方案的表示式,用括號表示運算優先。如果沒有解決方案,請輸出 -1。
輸入樣例:
2 3 12 12
輸出樣例:
((3-2)*12)+12
思路:
四個運算元,三個操作符,兩個括號,有以下五種計算模式
((A op B) op C) op D
(A op (B op C)) op D
A op (B op (C op D))
A op ((B op C) op D)
(A op B) op (C op D)
import java.io.BufferedInputStream; import java.util.Scanner; public class Main { static char[] op= {'#','+','-','*','/',}; static float cal(float x,float y,int op) { switch(op) { case 1:return x+y; case 2:return x-y; case 3:return x*y; case 4:return x/y; } return 0; } static float cal_model1(float i,float j,float k,float t,int op1,int op2,int op3) { float r1,r2,r3; r1 = cal(i,j,op1); r2 = cal(r1,k,op2); r3 = cal(r2,t,op3); return r3; } static float cal_model2(float i,r3; r1 = cal(j,op2); r2 = cal(i,r1,op1); r3 = cal(r2,op3); return r3; } static float cal_model3(float i,r3; r1 = cal(k,op3); r2 = cal(j,op2); r3 = cal(i,op1); return r3; } static float cal_model4(float i,op2); r2 = cal(r1,op3); r3 = cal(i,op1); return r3; } static float cal_model5(float i,op1); r2 = cal(k,op3); r3 = cal(r1,op2); return r3; } static int get24(int i,int j,int k,int t) { int op1,op2,op3; int flag = 0; for(op1=1;op1<=4;op1++) for(op2=1;op2<=4;op2++) for(op3=1;op3<=4;op3++) { if(cal_model1(i,op1,op3)==24){ System.out.printf("((%d%c%d)%c%d)%c%d\n",i,op[op1],op[op2],op[op3],t);flag = 1;return flag; } if(cal_model2(i,op3)==24){ System.out.printf("(%d%c(%d%c%d))%c%d\n",t);flag = 1;return flag; } if(cal_model3(i,op3)==24){ System.out.printf("%d%c(%d%c(%d%c%d))\n",t);flag = 1;return flag; } if(cal_model4(i,op3)==24){ System.out.printf("%d%c((%d%c%d)%c%d)\n",t);flag = 1;return flag; } if(cal_model5(i,op3)==24){ System.out.printf("(%d%c%d)%c(%d%c%d)\n",t);flag = 1;return flag; } } return 0; } public static void main(String[] args) { int x,y,m,n; int i,t; int[] in = new int[4]; int flag=0; Scanner sc = new Scanner(new BufferedInputStream(System.in)); for(i=0;i<4;i++) in[i] = sc.nextInt(); ok:for(i=0;i<4;i++){ for(j=0;j<4;j++){ if(j==i) continue; for(k=0;k<4;k++){ if(i==k||j==k) continue; for(t=0;t<4;t++){ if(t==i||t==j||t==k) continue; x = in[i]; y = in[j]; m = in[k]; n = in[t]; flag = get24(x,n); if(flag ==1)break ok; } } } } if(flag == 0) System.out.printf("-1\n"); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。