24点游戏算法
描述 |
问题描述:给出4个1-10的数字,通过加减乘除,得到数字为24就算胜利 |
---|---|
知识点 | 循环 |
运行时间限制 | 10M |
内存限制 | 128 |
输入 |
输入4个int整数 |
输出 |
返回能否得到24点,能输出true,不能输出false |
样例输入 | 7 2 1 10 |
样例输出 | true |
package com.oj5; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Oj { private static int calculate(int[] operator,int[] data){ int[] op = new int[3]; int[] da = new int[4]; int oppos = 0,dapos = 0; int posop = 0,posda = 0; da[dapos++] = data[posda++]; for(int i = 0;i <= 2; i++) if(operator[i]==1||operator[i]==2){ da[dapos++] = data[posda++]; op[oppos++] = operator[i]; //System.out.println("add"); }else if(operator[i]==3||operator[i]==4){ int left = da[--dapos]; int right = data[posda++]; int result; if(operator[i]==3) result = left*right; else result = left/right; da[dapos++] = result; //System.out.println(result); } int begin = 0; int result = da[begin++]; //System.out.println("oppos: "+oppos); // if(oppos==1) // System.out.println(op[0]); for(int i = 0;i < oppos; i++) if(op[i]==1){ //System.out.println(result+" ++"); result += da[begin++]; //System.out.println(result); }else if(op[i]==2){ //System.out.println(result+" --"); result -= da[begin++]; //System.out.println(result); } //System.out.println(op[0]); return result; // if(result==24) // return true; // else // return false; } static List<Integer> list = new ArrayList<Integer>(); private static void expression(int[] operator,int pos,int num,int[] data){ if(pos==num){ list.add(calculate(operator,data)); return ; } operator[pos] = 1; expression(operator,pos+1,num,data); operator[pos] = 2; expression(operator,pos+1,num,data); operator[pos] = 3; expression(operator,pos+1,num,data); operator[pos] = 4; expression(operator,pos+1,num,data); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] data = new int[4]; int[] operator = new int[3]; for(int i = 0;i < 4; i++) data[i] = in.nextInt(); expression(operator,0,3,data); for(int i = 0;i < list.size(); i++) if(list.get(i)==24){ System.out.println("true"); return ; } System.out.println("false"); } }
态度决定高度,细节决定成败,