enumeration (exhaustive) method
The essence of the enumeration method is to search for the correct solution from all the candidate answers. The use of this algorithm needs to meet two conditions:
(1): The number of candidate answers can be predetermined;
(2): The range of candidate answers must have a definite set before solving.
Example 1: Fill in the numbers game.
Java code description:
public static void main(String[] args) { int multi = 1; int result = 0; int i1, i2, i3, i4, i5; for (i1 = 1; i1 <= 9; i1++) { for (i2 = 0; i2 <= 9; i2++) { for (i3 = 0; i3 <= 9; i3++) { for (i4 = 0; i4 <= 9; i4++) { for (i5 = 0; i5 <= 9; i5++) { multi = i1 * 10000 + i2 * 1000 + i3 * 100 + i4 * 10 + i5; result = i5 * 100000 + i5 * 10000 + i5 * 1000 + i5 * 100 + i5 * 10 + i5; if (multi * i1 == result) { System.out.println(i1 + " " + i2 + " " + i3 + " " + i4 + " " + i5); System.out.println(" " + i1); System.out.println("-----------------"); System.out.println(i5 + " " + i5 + " " + i5 + " " + i5 + " " + i5); break; } } } } } } }
operation result:
Example 2: Fill operator:
Java code description:
private static void tysf() { int[] i = new int[5];// Array i is used to represent 4 operators int j; // loop variable int sign; // sign when accumulating int result = 0; // save the result value of the expression int count = 0; // counter, count the eligible schemes int[] num = new int[6]; // save operand float left, right; // save intermediate results char[] oper = { ' ', '+', '-', '*', '/' }; // operator System.out.println("Please enter five numbers"); Scanner sc = new Scanner(System.in); for (int ii = 1; ii <num.length; ii ++) { num[ii] = sc.nextInt(); } System.out.println("Please enter the result"); result = sc.nextInt(); // for (i[0] = 1; i[0] < 4; i[0]++) { //fill operator in loop 4, 1 means +, 2 means -, 3 means *, 4 means / // if ((i[0] < 4) || (num[1] != 0)) { //If the operator is /, the second operand cannot be 0 for (i[1] = 1; i[1] <= 4; i[1]++) { if ((i[1] < 4) || (num[2] != 0)) { for (i[2] = 1; i[2] <= 4; i[2]++) { if ((i[2] < 4) || (num[3] != 0)) { for (i[3] = 1; i[3] <= 4; i[3]++) { if ((i[3] < 4) || (num[4] != 0)) { for (i[4] = 1; i[4] <= 4; i[4]++) { if ((i[4] < 4) || (num[5] != 0)) { left = 0; right = num[1]; sign = 1; for (j = 1; j <= 4; j++) { switch (oper[i[j]]) { case '+': left = left + sign * right; sign = 1; right = num[j + 1]; break; case '-': left = left + sign * right; sign = -1; // subtraction by sign=-1 right = num[j + 1]; break; case '*': right = right * num[j + 1]; // implement multiplication break; case '/': right = right / num[j + 1]; // implement division break; } } if (left + sign * right == result) { count++; System.out.print(count + " "); for (j = 1; j <= 4; j++) { System.out.print(num[j] + "" + oper[i[j]]); } System.out.println("=" + result); } } } } } } } } } if (count == 0) { System.out.println("No matches"); } }
operation result: