Question:
I am new to Java (programming in Pascal) and I need to write a program to solve the following problem (something like a number puzzle):
AB + CC = DC
CE * FB = CEB
FF * GC = GHC
AB - CE = FF
CC + FB = GC
DC + CEB = GHC
P.S. Each character is one digit (from 0 to 9). Each digit can only be used once.
So I wrote the following program:
public class javaapplication1 {
public static void main(String[] args) {
boolean bb=false;
for (int h = 0; h < 10; h++) {
for (int g = 0; g < 10; g++) {
if (bb) {
break;
}
for (int f = 0; f < 10; f++) {
if (bb) {
break;
}
for (int e = 0; e < 10; e++) {
if (bb) {
break;
}
for (int d = 0; d < 10; d++) {
if (bb) {
break;
}
for (int c = 0; c < 10; c++) {
if (bb) {
break;
}
for (int b = 0; b < 10; b++) {
if (bb) {
break;
}
for (int a = 0; a < 10; a++) {
if (a*10 + b + c*10 + c == d*10 + c) {
if ((c*10+e)*(f*10+b)==(c*100+e*10+b)) {
if ((f*10+f)*(g*10+c)==g*100+h*10+c) {
if ((a*10+b)-(c*10+e) == f*10+f) {
if ((c*10+c)+(f*10+b) == g*10+c) {
if ((d*10+c)+(c*100+e*10+b) == g*100+h*10+c) {
if (a!=b && a!=c && a!=d && a!=e && a!=f && a!=g && a!=h) {
if (b!=c && b!=d && b!=e && b!=f && b!=g && b!=h) {
if (c!=d && c!=e && c!=f && c!=g && c!=h) {
if (d!=e && d!=f && d!=g && d!=h) {
if (e!=f && e!=g && e!=h) {
if (f!=g && f!=h) {
if (g!=h) {
bb = true;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
System.out.println(f);
System.out.println(g);
System.out.println(h);
break;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
It works and produces the correct results, however I'm sure it's spelled wrong as the solution itself is stupid – pure bribery. Please show me how to optimize this program. Z.Y. I wrote a large number of if-s to a greater extent for greater code clarity for myself personally.
Answer:
- There is no need to make a complex
break
through a boolean variable.return
is enough, it will break all loops. - The condition "Each digit can be used only once" must be checked not at the very last, but at the stage of enumeration. So you will only have
10!/2!=10*9*8*7*6*5*4*3
checks, not10^8
.- Define the set of all digits.
- In the outer loop iterate over this set.
- In the next loop, iterate over the set from the previous loop without the digit that was selected in the previous loop.
- In the next loop, iterate over the set from the previous loop without the digit that was selected in the previous loop … and so on.
- Conditions can be isolated and stored as a list of methods (lambdas), and then checked in a loop.