您的位置:首页 > 编程语言 > Java开发

编程之美1.1624点游戏解法一java版

2016-06-01 13:43 211 查看
书中给出的第一种解法的java版

根据给的思路可以得出是否能算出24的结论,但是没办法输出表达式

值得注意的地方:1.将两个取出来的数从原数组中去掉,代码中采用的方法很巧妙,用数组后面的值和新计算出的值来代替,这样做的好处是还原数组也很简单

                                 2.输出表达式的地方还没想出怎么解决

扩展问题一:3,3,8,8程序给出的结论是false

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Test;

import java.math.BigDecimal;
import static java.math.BigDecimal.ROUND_HALF_DOWN;
import java.util.*;

/**
*
* @author Administrator
*/
public class PointsGame {

static double[] number = {9, 9, 6, 2};
static String[] result =new String[4];

public static void main(String[] args) {
for(int i =0;i<4;i++){
result[i] ="";
}
boolean flag = pointsGame(4);
System.out.println("flag="+flag);
for(int i =0;i<4;i++){
System.out.println(result[i]);
}
}

private static boolean pointsGame(int n) {
if (n < 2) {
if (number[0] == 24) {
return true;
} else {
return false;
}
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
double a, b;
String expa,expb;
a = number[i];
b = number[j];
number[j]=number[n-1];

expa=result[i];
expb=result[j];
result[j]=result[n-1];

result[i]="("+expa+"+"+expb+")";
number[i] = a+b;
if(pointsGame(n-1))
return true;

result[i]="("+expa+"-"+expb+")";
number[i]=a-b;
if(pointsGame(n-1))
return true;

result[i]="("+expb+"-"+expa+")";
number[i]=b-a;
if(pointsGame(n-1))
return true;

result[i]="("+expa+"*"+expb+")";
number[i]=a*b;
if(pointsGame(n-1))
return true;

if(b!=0){
result[i]="("+expa+"/"+expb+")";
number[i]=a/b;
if(pointsGame(n-1))
return true;
}
if(a!=0){
result[i]="("+expb+"/"+expa+")";
number[i]=b/a;
if(pointsGame(n-1))
return true;
}
number[i]=a;
number[j]=b;
result[i]=expa;
result[j]=expb;

}
}
return false;
}

}
                运行结果:true (((+)-)*)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: