Question--
“Write a program that outputs all possibilities to put + or - or nothing between the numbers 1, 2, …, 9 (in this order) such that the result is always 100”
Java
public static void main(String[] args) throws IOException, ScriptException {
String[] o = { "", "-", "+" };
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
int sum = 0;
for (int i = 5; i <= combinations; i++) {
int tmp = Integer.parseInt(Integer.toString(i, 3), 10); //translate to base 3
String str = String.format("%08d", tmp);
int[] p = new int[8];
for (int j = 0; j < 8; j++) {
p[j] = str.charAt(j) - 48;
}
String resultS = "1" + o[p[0]] + "2" + o[p[1]] + "3" + o[p[2]] + "4" + o[p[3]] + "5" + o[p[4]] + "6"
+ o[p[5]] + "7" + o[p[6]] + "8" + o[p[7]] + "9";
int result = (Integer) engine.eval(resultS);
if (result == 100) {
sum++;
solutions.add(resultS);
}
}
for (int i = 0; i < solutions.size(); i++) {
System.out.print(solutions.get(i) + "\n");
}
System.out.print(sum);
}