Enum can help here.
Iโm not sure that everything worked out for me, because Iโm not sure that I realized all the possible bracketing, but now it looks complete.
enum Op { Add("+") { @Override int op(int a, int b) { return a + b; } }, Sub("-") { @Override int op(int a, int b) { return a - b; } }, Mul("*") { @Override int op(int a, int b) { return a * b; } }, Div("/") { @Override int op(int a, int b) { // Insane value for / 0 to ensure unlikely to match. return b != 0 ? a / b : Integer.MAX_VALUE; } }; final String asString; Op(String asString) { this.asString = asString; } public String toString() { return asString; } abstract int op(int a, int b); } private void tryAllOrders(int a, int b, int c, int d, Op op1, Op op2, Op op3, int target) { if (op3.op(op2.op(op1.op(a, b), c), d) == target) { System.out.println(" ((" + a + op1 + b + ")" + op2 + c + ")" + op3 + d + "=" + target); } if (op3.op(op1.op(a, op2.op(b, c)), d) == target) { System.out.println(" (" + a + op1 + "(" + b + op2 + c + "))" + op3 + d + "=" + target); } if (op2.op(op1.op(a, b), op3.op(c, d)) == target) { System.out.println(" (" + a + op1 + b + ")" + op2 + "(" + c + op3 + d + ")=" + target); } if (op1.op(a, op3.op(op2.op(b, c), d)) == target) { System.out.println(" " + a + op1 + "((" + b + op2 + c + ")" + op3 + d + ")=" + target); } if (op1.op(a, op2.op(b, op3.op(c, d))) == target) { System.out.println(" " + a + op1 + "(" + b + op2 + "(" + c + op3 + d + "))=" + target); } } private void tryAllOps(int a, int b, int c, int d, int target) { for (Op op1 : Op.values()) { for (Op op2 : Op.values()) { for (Op op3 : Op.values()) { tryAllOrders(a, b, c, d, op1, op2, op3, target); } } } } public void test() { int target = 24; for (int a = 1; a <= 13; a++) { for (int b = 1; b <= 13; b++) { for (int c = 1; c <= 13; c++) { for (int d = 1; d <= 13; d++) { tryAllOps(a, b, c, d, target); } } } } }
He prints:
((1+1)+1)*8=24 (1+(1+1))*8=24 (1+1)*(1+11)=24 ((1+1)*1)*12=24 (1+(1*1))*12=24 (1+1)*(1*12)=24 ... 7+((11*8)/5)=24 ((7+11)*8)/6=24 ((7-11)+8)*6=24 (7-(11-8))*6=24 ((7+11)/8)*12=24 (7/(11-8))*12=24 ... ((13/13)*13)+11=24 (13/13)*(13+11)=24 (13/(13/13))+11=24 ((13+13)/13)*12=24 (13-(13/13))+12=24 13-((13/13)-12)=24
Overall result of 67,752 .