- Sections 13.5 - 13.6, Worked Example 13.1, Worked Example 13.2

**Problem:**to compute the value of arithmetic expressions such as3 + 4 * 5 (3 + 4) * 5 1 - (2 - (3 - (4 - 5)))

- Computing expression is complicated
`*`and`/`bind more strongly than`+`and`-`- Parentheses can be used to group subexpressions

- An expression can broken down into a sequence of terms, separated by
`+`or`-` - Each term is broken down into a sequence of factors, separated by
`*`or`/` - Each factor is either a parenthesized expression or a number
- The syntax trees represent which operations should be carried out first

- In a mutual recursion, a set of cooperating methods calls each other repeatedly
- To compute the value of an expression, implement 3 methods that call each other recursively:
`getExpressionValue``getTermValue``getFactorValue`

Why do we need both terms and factors?

- Factors are combined by multiplicative operators (
`*`and`/`), terms are combined by additive operators (`+`,`-`). - Terms are combined by multiplicative operators (
`*`and`/`), factors are combined by additive operators (`+`,`-`). - We need both so that multiplication can bind more strongly than addition.
- We need both so that we can have mutual recursion

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?

- getExpressionValue
- getTermValue
- getFactorValue
- main

To see the mutual recursion clearly, trace through the expression `(3+4)*5`:

`getExpressionValue`calls`getTermValue``getTermValue`calls`getFactorValue``getFactorValue`consumes the`(`input`getFactorValue`calls`getExpressionValue``getExpressionValue`returns eventually with the value of`7`, having consumed`3 + 4`. This is the recursive call.

`getFactorValue`consumes the`)`input`getFactorValue`returns`7`

`getTermValue`consumes the inputs`*`and`5`and returns`35`

`getExpressionValue`returns`35`

Why does the expression parser use mutual recursion?

- To compute the value of an arithmetic expression more efficiently than with a loop
- To make * and / bind stronger than + and -
- To handle both operators such as * and / and numbers such as 2 and 3
- To handle parenthesized expressions, such as
`2+3*(4+5)`

- Build up partial solution
- Accept if it is an actual solution
- Check if it could continue being a solution
- If not, abandon it
- If so, extend it
- Extension can yield one or more partial solutions
- Pursue each of them recursively

```
Solve(partialSolution)
Examine(partialSolution).
If accepted
Add partialSolution to the list of solutions.
Else if continuing
For each p in extend(partialSolution)
Solve(p).
```

- Position eight queens on a chess board so that none of them attacks another
- There are no two queens on the same row, column, or diagonal
- Backtracking: Put a queen somewhere and keep going until it fails
- We know that there must be one queen on each row (why?)
- Put a queen on row 1, then one on row 2, ...

How many solutions of the four queens problem are in the preceding figure?

- 0
- 1
- 2
- 3

- Array of queens
- Partial solution is accepted if the queens don't attach each other
- Extending a partial solution: add another queen
public class PartialSolution { private Queen[] queens; public int examine() { . . . } public PartialSolution[] extend() { . . . } }

- Check whether two queens attack each other:

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; } }

- Make copies and add a queen in each column
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?

- 92
- 720
- 4320
- Something else