3 + 4 * 5 (3 + 4) * 5 1 - (2 - (3 - (4 - 5)))
Why do we need both terms and factors?
public int getExpressionValue() { int value = getTermValue(); boolean done = false; while (!done) { String next = tokenizer.peekToken(); if ("+".equals(next) || "-".equals(next)) { tokenizer.nextToken(); // Discard "+" or "-" int value2 = getTermValue(); if ("+".equals(next)) value = value + value2; else value = value - value2; } else { done = true; } } return value; }
The getTermValue method calls getFactorValue in the same way, multiplying or dividing the factor values
public int getTermValue() { int value = getFactorValue(); boolean done = false; while (!done) { String next = tokenizer.peekToken(); if ("*".equals(next) || "/".equals(next)) { tokenizer.nextToken(); // Discard "*" or "/" int value2 = getFactorValue(); if ("*".equals(next)) value = value * value2; else value = value / value2; } else { done = true; } } return value; }
public int getFactorValue() { int value; String next = tokenizer.peekToken(); if ("(".equals(next)) { tokenizer.nextToken(); // Discard "(" value = getExpressionValue(); tokenizer.nextToken(); // Discard ")" } else { value = Integer.parseInt(tokenizer.nextToken()); } return value; }
What happens if you try to parse the illegal expression 3+4*)5? Specifically, which method throws an exception?
To see the mutual recursion clearly, trace through the expression (3+4)*5:
Why does the expression parser use mutual recursion?
Solve(partialSolution)
Examine(partialSolution).
If accepted
Add partialSolution to the list of solutions.
Else if continuing
For each p in extend(partialSolution)
Solve(p).
How many solutions of the four queens problem are in the preceding figure?
public class PartialSolution { private Queen[] queens; public int examine() { . . . } public PartialSolution[] extend() { . . . } }
public int examine() { for (int i = 0; i < queens.length; i++) { for (int j = i + 1; j < queens.length; j++) { if (queens[i].attacks(queens[j])) { return ABANDON; } } } if (queens.length == NQUEENS) { return ACCEPT; } else { return CONTINUE; } }
public PartialSolution[] extend() { // Generate a new solution for each column PartialSolution[] result = new PartialSolution[NQUEENS]; for (int i = 0; i < result.length; i++) { int size = queens.length; // The new solution has one more row than this one result[i] = new PartialSolution(size + 1); // Copy this solution into the new one for (int j = 0; j < size; j++) { result[i].queens[j] = queens[j]; } // Append the new queen into the ith column result[i].queens[size] = new Queen(size, i); } return result; }
Suppose it was ok for queens to be in the same diagonal. Modify this program to count (but not display) the number of possible solutions for 6 queens. What do you get?