折腾了一个中午写了一个24点的算法,试验了一下效果还不错,这个算法没有啥技巧也就是把全部的可能性给算一遍,代码如下:
/**
* @author 百岁(baisui@taobao.com)
* @date 2013-3-27
*/
public class Test24 {
/**
* @param args
*/
public static void main(String[] args) {
// 需要计算的24点的四个值放置在一个数组中
int[] param = new int[] { 2, 6, 5, 10 };
for (int i = 0; i < param.length; i++) {
for (int j = 0; j < param.length; j++) {
if (i == j) {
continue;
}
// System.out.println("i:" + param[i] + ",j:" + param[j]);
for (Comput opr : computAry) {
int degree2 = opr.comput(param[i], param[j]);
for (int k = 0; k < param.length; k++) {
Set<Integer> all = new HashSet<Integer>();
all.add(i);
all.add(j);
all.add(k);
if (all.size() < 3) {
continue;
}
for (Comput opr2 : computAry) {
int degree3 = opr2.comput(degree2, param[k]);
for (int m = 0; m < param.length; m++) {
all = new HashSet<Integer>();
all.add(i);
all.add(j);
all.add(k);
all.add(m);
if (all.size() < 4) {
continue;
}
for (Comput opr3 : computAry) {
if (opr3.comput(degree3, param[m]) == 24) {
// System.out.println("i:" + param[i]
// + ",j:" + param[j] + ",k="
// + param[k] + ",m=" + param[m]);
System.out.println("" + param[i]
+ opr.getSymbol() + param[j]
+ opr2.getSymbol() + param[k]
+ opr3.getSymbol() + param[m]);
}
}
}
}
}
}
}
}
}
static abstract class Comput {
abstract int comput(int a, int b);
abstract char getSymbol();
}
static class Plus extends Comput {
@Override
int comput(int a, int b) {
return a + b;
}
@Override
char getSymbol() {
return '+';
}
}
static class Subtraction extends Comput {
@Override
int comput(int a, int b) {
return a - b;
}
@Override
char getSymbol() {
return '-';
}
}
static class Times extends Comput {
@Override
int comput(int a, int b) {
return a * b;
}
@Override
char getSymbol() {
return '*';
}
}
static class Division extends Comput {
@Override
int comput(int a, int b) {
return 0;
}
@Override
char getSymbol() {
return '/';
}
}
final static Comput[] computAry = new Comput[] { new Plus(),
new Subtraction(), new Times(), new Division() };
}