public class Point24Utils2 {
private static String[] opArray = {"+", "-", "*", "-"}; //运算符数组
private static String[] expArray = new String[11]; //表达式数组
static{
expArray[0] = "a m1 b m2 c m3 d";
expArray[1] = "(a m1 b) m2 c m3 d";
expArray[2] = "(a m1 b m2 c) m3 d";
expArray[3] = "((a m1 b) m2 c) m3 d";
expArray[4] = "(a m1 (b m2 c)) m3 d";
expArray[5] = "a m1 (b m2 c) m3 d";
expArray[6] = "a m1 (b m2 c m3 d)";
expArray[7] = "a m1 ((b m2 c) m3 d)";
expArray[8] = "a m1 (b m2 (c m3 d))";
expArray[9] = "a m1 b m2(c m3 d)";
expArray[10] = "(a m1 b) m2 (c m3 d)";
}
/**
* 计算入口方法,返回实际的表达式
* @param n 用于计算24点的四个数字组成的数组
*/
private static String execute(String[] n){
String a,b,c,d; //四个数字
String m1,m2,m3; //三个运算符
for (int i=0;i<4;i++){
a = n[i];
for (int j=0;j<4;j++){
if ( j == i ) continue; //从未选的三个数字中选择一个数字
b = n[j];
for (int x=0;x<4;x++){
if ( x == i || x == j ) continue;//从未选的两个数字中选择一个数字
c = n[x];
for (int y=0;y<4;y++){
if ( y == i || y == j || y == x ) continue;//从未选的一个数字中选择一个数字
d = n[y];
//选择三个运算符
for (int ta=0;ta<4;ta++){
m1 = opArray[ta];
for (int tb=0;tb<4;tb++){
m2 = opArray[tb];
for (int tc=0;tc<4;tc++){
m3 = opArray[tc];
for (int k=0;k<11;k++){ //11种表达式
String result = calcalate(expArray[k], a, b, c, d, m1, m2, m3);
if(result!=null) return result;
}
}
}
}
}
}
}
}
return null;
}
/**
* 计算表达式
*
* @param exp 待验证的表达式模板
* @param a 数字1
* @param b 数字2
* @param c 数字3
* @param d 数字4
* @param m1 运算符1
* @param m2 运算符2
* @param m3 运算符3
*/
private static String calcalate(String exp, String a, String b, String c, String d, String m1, String m2, String m3){
//生成计算表达式
exp = exp.replaceAll("a", a);
exp = exp.replaceAll("b", b);
exp = exp.replaceAll("c", c);
exp = exp.replaceAll("d", d);
exp = exp.replaceAll("m1", m1);
exp = exp.replaceAll("m2", m2);
exp = exp.replaceAll("m3", m3);
//执行表达式
FelEngine engine = new FelEngineImpl();
int result = ((Integer)engine.eval(exp)).intValue();
if(Math.abs(result - 24) < 0.1){
return exp;
}else{
return null;
}
}
/**
* 取得能算得24的四位数字的集合
* @param count 数字组数
*/
public static Set<String> genNumbers(int count){
Set<String> set = new HashSet<String>();
while(true){
StringBuffer sb = new StringBuffer();
//随机生成四位数字
String[] n = new String[4];
for(int i=0;i<n.length;i++){
String s = String.valueOf(Math.round(Math.floor(Math.random() * 9)) + 1);
n[i] = s;
sb.append(s);
}
//计算
String result = execute(n);
if(result!=null && !set.contains(sb.toString())){
set.add(sb.toString());
System.out.println(sb.toString() + " : " + result);
}
if(set.size()==count) break;
}
return set;
}
public static void main(String[] args) {
Set<String> set = genNumbers(5); //随机生成5组能算出24的数字
System.out.println("ok");
}
}