思路:
- 一开始我们随机生成四个数字A、B、C、D,选择其中任意一个数字,暂记为A;
- 将A和B、C、D进行加减乘除运算,并把结果存储起来;
- 由于每次都是选择的两张牌,并且最后运算出的结果都是一张牌,所以未知数规模在不断减小;
- 反复计算,直到得到24点即可;
实现代码:
package ergodic;
import java.util.*;
/**
* @ Author :heywecome
* @ Date :Created in 14:14 2018/12/21
* @ Description:${description}
* @ Modified By:
* @Version: $version$
*/
import java.util.*;
public class SolutionOf24 {
private int[] num = new int[4]; // 存储最初的四个数字
private String solution; // 最终的表达式
public boolean judgePoint24(int[] nums) {
num = nums;
List<Double> list = new ArrayList<>();
for (int i : nums) {
list.add((double) i);
}
System.out.println("参与运算的四个值为:"+list.toString());
return dfs(list);
}
// 每次dfs都是选取两张牌
private boolean dfs(List<Double> list) {
if (list.size() == 1) {
// 如果此时list只剩下了一张牌
if (Math.abs(list.get(0)- 24.0) < 0.001) {
return true;
}
return false;
}
// 选取两张牌
for(int i = 0; i < list.size(); i++) {
for(int j = i + 1; j < list.size(); j++) {
// 对于每下一个可能的产生的组合
for (double c : compute(list.get(i), list.get(j))) {
// System.out.println(c);
List<Double> nextRound = new ArrayList<>();
// 将他们加入到下一个list循环中去
nextRound.add(c);
for(int k = 0; k < list.size(); k++) {
if(k == j || k == i) continue; // 不可以等于之前的牌
nextRound.add(list.get(k)); // 选择出剩余的牌,加入到下一次的循环中
}
if(dfs(nextRound)) return true;
}
}
}
return false;
}
// 计算下一个可能产生的组合
private List<Double> compute(double a, double b) {
List<Double> res = Arrays.asList(a+b,a-b,b-a,a*b,a/b,b/a);
return res;
}
/**
* 存储运算表达式以及每个结果的值
* @param formula
* @param temp
* @param result
*/
private void save(String formula,double temp, HashMap<String,Double> result){
// 将运算表达式还有结果存储起来
result.put(formula,temp);
}
//根据value值获取到对应的一个key值
//此处我本来打算通过存储每个运算过程,并把结果存储,最后通过逆推的方式获得完整的推导过程
//由于时间不充分,暂时未实现,待续...
public static String getKey(HashMap<String,Double> map,double value) {
String key = null;
//Map,HashMap并没有实现Iteratable接口.不能用于增强for循环.
for (String getKey : map.keySet()) {
if (map.get(getKey) == value) {
key = getKey; // 要进行判断 这个值是否对应的是四个数字组成的元素
String[] temp = key.split("\\+|-|\\*|/");
}
}
return key;
//这个key肯定是最后一个满足该条件的key
}
public static void main(String[] args){
int a = (int)(Math.random()*9+1);
int b = (int)(Math.random()*9+1);
int c = (int)(Math.random()*9+1);
int d = (int)(Math.random()*9+1);
int[] nums = {a,b,c,d};
// int[] nums = {7,3,9,7};
SolutionOf24 solution = new SolutionOf24();
System.out.println("是否可以组成24点?"+solution.judgePoint24(nums));
}
}
结果截图: