这是我最终得到的实现,但首先是对问题解决方案的解释:
- 基本情况(如 larsmans 和 Jan Dvorak 所说)是所有“_”都用运算符(例如“+”)填充。
- 该函数调用自身,每次都添加另一个参数,直到达到不正确的基本情况(例如“6+3+5+7+4-8=13”)或得到正确答案。
- 如果基本情况不正确,那么我们会不断弹出级别,我们可以使用可以更改的运算符来达到某个级别。
这是代码:
class GapFill {
private static String numbers; //E.g. 6_5_4=15
private static String[] blank; //Array of operators to go in the blanks
//Where:
//p = plus
//m = minus
//d = divide
//t = times
private static String[] operators = {"p", "m", "d,", "t"};
public static void main(String[] args) {
numbers = args[0];
blank = new String[numbers.split("_").length - 1];
if(dfs(0)) { //If a solution was found
int count = 0;
while(numbers.indexOf("_")!=-1) {
int index = numbers.indexOf("_");
numbers = numbers.substring(0,index)+blank[count]+numbers.substring(index+1);
count++;
}
System.out.println(numbers);
}
}
private static boolean dfs(int i) {
if(i == blank.length) { //base case: filled in all the blanks
return solveEquation();
}
for(String op : operators) {
blank[i] = op;
if(dfs(i + 1)) {
return true;
}
}
blank[i] = "_"; //restore to previous state
return false;
}
private static boolean solveEquation() {
String[] eachNumber = numbers.substring(0, numbers.indexOf("=")).split("_");
String finalResult = numbers.substring(numbers.indexOf("=")+1, numbers.length());
double currentResult = Double.parseDouble(eachNumber[0]);
for(int i=1;i<eachNumber.length;i++) {
String op = blank[i-1];
if(op==operators[0]) {
currentResult = currentResult + Integer.parseInt(eachNumber[i]);
} else if(op==operators[1]) {
currentResult = currentResult - Integer.parseInt(eachNumber[i]);
} else if(op==operators[2]) {
currentResult = currentResult / Integer.parseInt(eachNumber[i]);
} else if(op==operators[3]) {
currentResult = currentResult * Integer.parseInt(eachNumber[i]);
}
}
return (currentResult==Integer.parseInt(finalResult));
}
}
的输出java GapFill 6_3_5_7_4_8=13
是6m3p5m7p4p8=13
。
使用“p,m,d,t”符号代替“+,-,÷,×”,因为终端不喜欢 × 或 ÷