24点游戏的算法
判断是否可以算出24点,并输出一个可以算出24点的公式
import java.util.HashMap; import java.util.Map; import java.util.Stack; /** * 1-13任取4个数,结果+-/*计算是否可以得到24,可以包括括号
*@author javalixue
*/ public class TwentyFour { static Stack<Map<String, Object>> stack = new Stack<Map<String, Object>>(); double[] arr = new double[4]; public static void main(String[] args) { TwentyFour t = new TwentyFour(); System.out.println(t.can24(6, 3, 8, 8)); String formula = ""; for (int i = stack.size() - 1; i >= 0; i--) { Map<String, Object> m = stack.get(i); String a = String.valueOf(m.get("a")); String b = String.valueOf(m.get("b")); Calculator c = (Calculator) m.get("calculator"); if (i == stack.size() - 1) { formula = getCalculator(a, b, c); } else { formula = getCalculator(formula, b, c); } } System.out.println(formula); } static String getCalculator(String a, String b, Calculator c) { switch (c) { case Add: return "(" + a + "+" + b + ")"; case Minus: return "(" + a + "-" + b + ")"; case Multipy: return "(" + a + "*" + b + ")"; case Divide: return "(" + a + "/" + b + ")"; case AntiMinus: return "(" + b + "-" + a + ")"; case AntiDivide: return "(" + b + "/" + a + ")"; default: break; } return null; }
public boolean cal(int n) {
if (n == 1) { if (Math.abs(arr[0] - 24) < 1e-6) { return true; } return false; } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { double tmp1 = arr[i]; double tmp2 = arr[j]; arr[j] = arr[n - 1];// 用最后一位替换 for (Calculator c : Calculator.values()) { arr[i] = calculate(tmp1, tmp2, c); if (cal(n - 1)) { Map<String, Object> m = new HashMap<String, Object>(); m.put("a", (int) tmp1); m.put("calculator", c); m.put("b", (int) tmp2); stack.add(m); return true; } } // 恢复数组 arr[i] = tmp1; arr[j] = tmp2; } } return false; } public boolean can24(int a, int b, int c, int d) { this.arr = new double[] { a, b, c, d }; return cal(4); } public double calculate(double a, double b, Calculator c) { switch (c) { case Add: return a + b; case Minus: return a - b; case Multipy: return a * b; case Divide: return a / b; case AntiMinus: return b - a; case AntiDivide: return b / a; default: return 0; } } } enum Calculator { Add, Minus, Multipy, Divide, AntiMinus, AntiDivide
}