কম্পিউটার বিজ্ঞান · বই 4 · স্নাতক দ্বিতীয় বর্ষ

University Computer Science — Year 2

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 2 · স্নাতক দ্বিতীয় বর্ষ

28Search and Games

The sliding-tile puzzle has eight numbered tiles in a 3×33 \times 3 frame and one empty cell; a move slides a tile into the empty cell, and the goal is to put the tiles in order. A program can try every sequence of moves, but how many it has to try depends on how it chooses:

if __name__ == "__main__":
    rng = random.Random(3)
    print("moves  BFS expanded  A* misplaced  A* Manhattan")
    for walk in [10, 20, 40, 80, 3000]:
        start = scrambled(walk, rng)
        path, n_bfs = bfs(start, lambda s: s == GOAL, successors)
        _, c1, n_mis = astar(start, lambda s: s == GOAL, successors, misplaced)
        _, c2, n_man = astar(start, lambda s: s == GOAL, successors, manhattan)
        assert len(path) - 1 == c1 == c2
        print(f"{c1:5} {n_bfs:13} {n_mis:13} {n_man:13}")
Listing 28.1. Five scrambled puzzles solved three ways, counting the states each search expands code/bachelor-2/28-search-and-games/listings/eight_puzzle.py
$ python eight_puzzle.py
moves  BFS expanded  A* misplaced  A* Manhattan
    8           226            21            14
   10           441            53            32
   16         13741           699           141
   20         44097          3501           772
   24        122340         18619          2392
Output 28.1. The same shortest solutions, found after very different amounts of work.

All three searches return a shortest solution, and the third expands fifty times fewer states than the first on the hardest puzzle. The difference is an estimate of the distance left, used carefully enough that the answer stays optimal. The second half of the chapter adds an opponent: in noughts and crosses, or in a race between a robot and a rival through the town, each player chooses in turn, and a program can still compute who wins, and how.

You already know

The Year 1 volume: breadth-first and depth-first search; Dijkstra’s algorithm for shortest paths with non-negative weights, and its proof; priority queues kept as binary heaps; backtracking. The grade 10 volume: graphs, paths and trees.

28.1 State spaces

Definition 28.1 (State space, search problem, goal test)

A search problem is given by a set of states, a start state, a goal test that says whether a state is a goal, and for each state its successors, each reached by an action of cost c>0c > 0. The states and the actions form a directed graph, the state space; a solution is a path from the start to a goal, and an optimal solution one of least total cost.

The state space is usually never built: the 8-puzzle has 9!/2=181,4409!/2 = 181{,}440 reachable states, chess far more than any memory holds. The program knows only the start and a function that lists successors; the graph is implicit, and a search builds the part it visits.

Part of the 8-puzzle’s state space. The start has four successors, one per tile that can slide; each is labelled with its Manhattan distance h, the sum over the tiles of their distances to their places. The thick path is the solution of two moves; h points straight at it.
Part of the 8-puzzle’s state space. The start has four successors, one per tile that can slide; each is labelled with its Manhattan distance hh, the sum over the tiles of their distances to their places. The thick path is the solution of two moves; hh points straight at it.
def bfs(start, is_goal, successors):
    parent, queue, expanded = {start: None}, deque([start]), 0
    while queue:
        s = queue.popleft()
        expanded += 1
        if is_goal(s):
            return path_to(parent, s), expanded
        for t, _ in successors(s):
            if t not in parent:
                parent[t] = s
                queue.append(t)
    return None, expanded
Listing 28.2. Breadth-first search in an implicit graph, counting the states expanded code/bachelor-2/28-search-and-games/listings/state_space.py

Breadth-first search expands the states in order of depth, so it finds a solution with fewest actions. If each state has at most bb successors and the shallowest goal is at depth dd, it may expand 1+b+⋯+bd=O(bd)1 + b + \dots + b^d = O(b^d) states, and keeps them all in memory. Depth-first search keeps only the current path, but may go down forever, or find a long solution first.

Definition 28.2 (Iterative deepening)

Iterative deepening runs a depth-first search limited to depth 00, then 11, then 22, and so on, until a limit at which it finds a goal.

It finds a solution with fewest actions, like breadth-first search, while keeping only a path of d+1d + 1 states. Repeating the shallow levels costs little: with b≥2b \geq 2 the last level holds at least half of all the states up to it, and the total work is O(bd)O(b^d) again (Exercises 28.3 and 28.4).

def depth_limited(s, is_goal, successors, limit, path, count):
    count[0] += 1
    if is_goal(s):
        return list(path)
    if limit == 0:
        return None
    for t, _ in successors(s):
        if t not in path:  # no cycles along the current path
            path.append(t)
            found = depth_limited(t, is_goal, successors, limit - 1, path, count)
            path.pop()
            if found:
                return found
    return None


def iterative_deepening(start, is_goal, successors, max_depth=50):
    count = [0]
    for limit in range(max_depth + 1):
        found = depth_limited(start, is_goal, successors, limit, [start], count)
        if found:
            return found, count[0]
    return None, count[0]
Listing 28.3. Depth-limited search, which never revisits a state of the current path, and iterative deepening code/bachelor-2/28-search-and-games/listings/state_space.py

28.2 Uniform-cost search

When actions have different costs, as roads have different lengths, fewest actions is not cheapest.

Definition 28.3 (Uniform-cost search)

Uniform-cost search keeps a priority queue of states ordered by g(s)g(s), the cost of the cheapest path to ss found so far. It repeatedly removes a state of smallest gg, marks it expanded, stops if it is a goal, and otherwise updates gg for its successors not yet expanded.

It is Dijkstra’s algorithm of the Year 1 volume, run on an implicit graph and stopped at the first goal.

Theorem 28.4 (Uniform-cost search)

With positive action costs, uniform-cost search expands states in order of non-decreasing distance from the start; when it expands a state ss, g(s)g(s) is the distance to ss. In particular the first goal expanded is reached by an optimal solution.

Proof. This is the invariant of Dijkstra’s algorithm, proved in the Year 1 volume: if a state ss were expanded with g(s)g(s) larger than its distance, the first state uu of an optimal path to ss that is not yet expanded would have, from its expanded predecessor, g(u)g(u) equal to its distance, at most the distance of ss, which is less than g(s)g(s), so uu would have been removed from the queue first. A goal expanded first is at the least distance among the goals: any closer goal would have been expanded before. ∎

28.3 Heuristics and A*

Uniform-cost search spreads in every direction. Most problems come with knowledge of the direction to go: the straight-line distance to the destination, or how far each tile is from its place.

Definition 28.5 (Heuristic, admissible, consistent)

A heuristic is a function h≥0h \geq 0 on states that estimates the cost of reaching a goal, with h=0h = 0 on goals. Write h∗(s)h^*(s) for the true least cost from ss to a goal. The heuristic is admissible if h(s)≤h∗(s)h(s) \leq h^*(s) for every ss: it never overestimates. It is consistent if h(s)≤c+h(t)h(s) \leq c + h(t) for every action from ss to tt of cost cc.

Proposition 28.6 (Consistent implies admissible)

A consistent heuristic is admissible.

Proof. Exercise 28.8: follow an optimal path from ss to a goal and add the inequalities. ∎

Method 28.7 (A*)

Uniform-cost search in which the priority of a state ss is f(s)=g(s)+h(s)f(s) = g(s) + h(s), the cost so far plus the estimate of the cost left.

def astar(start, is_goal, successors, h=lambda s: 0, order=None):
    """A*: expand the state of smallest g + h. With h = 0, uniform-cost search.
    Returns (path, cost, number of states expanded); order lists them if given."""
    g, parent = {start: 0}, {start: None}
    frontier, done, tie = [(h(start), 0, start)], set(), 0
    while frontier:
        _, _, s = heapq.heappop(frontier)
        if s in done:
            continue  # a stale entry: s was reached again more cheaply
        done.add(s)
        if order is not None:
            order.append(s)
        if is_goal(s):
            return path_to(parent, s), g[s], len(done)
        for t, cost in successors(s):
            if t not in done and g[s] + cost < g.get(t, float("inf")):
                g[t], parent[t] = g[s] + cost, s
                tie += 1  # a counter breaks ties without comparing states
                heapq.heappush(frontier, (g[t] + h(t), tie, t))
    return None, float("inf"), len(done)
Listing 28.4. A*: uniform-cost search when h=0h = 0 code/bachelor-2/28-search-and-games/listings/state_space.py

Theorem 28.8 (Optimality of A*)

If hh is consistent, A* as in Listing 28.4, which never expands a state twice, returns an optimal solution, and it expands the states in order of non-decreasing ff.

Proof. Give each action from ss to tt the new cost c′=c−h(s)+h(t)c' = c - h(s) + h(t), which is ≥0\geq 0 by consistency. Along any path from the start s0s_0 to a state tt, the new costs add up to the old cost minus h(s0)h(s_0) plus h(t)h(t): the middle terms cancel. So the new distance to tt is g(t)−h(s0)+h(t)g(t) - h(s_0) + h(t), the priority of A* minus a constant. A* is therefore uniform-cost search on the new costs, and by Theorem 28.4 (whose proof needs only non-negative costs) it expands states in order of new distance, that is of ff, with gg exact. On goals h=0h = 0, so the order of new distances among goals is that of true distances, and the first goal expanded is an optimal one. ∎

If hh is only admissible, A* that may expand a state again, when it finds a cheaper path to it, is still optimal; the listing, which never expands a state twice, may then return a longer path. A heuristic that overestimates loses the guarantee altogether (Exercise 28.2).

For the 8-puzzle, the number of misplaced tiles and the Manhattan distance are both consistent: one move changes one tile’s position by one cell, so it changes either heuristic by at most 11 (Exercise 28.9). The Manhattan distance is never smaller than the number of misplaced tiles, and Output 28.1 shows what that buys: the closer hh is to h∗h^*, the fewer states A* expands.

The five puzzles of  on a logarithmic scale. All three counts grow exponentially with the depth; a better heuristic lowers the rate of growth, not only the level.
The five puzzles of Output 28.1 on a logarithmic scale. All three counts grow exponentially with the depth; a better heuristic lowers the rate of growth, not only the level.

On the town’s map, the straight-line distance between two places is consistent, by the triangle inequality, and no road is shorter than the straight line between its ends.

$ python town_astar.py
30 places; roads shorter than the straight line: 0
Bus Depot to Football Ground: 2430 m, straight line 2051 m; expanded 5 (Dijkstra) and 3 (A*)
   route: 16-4-15
Lighthouse Café to West Gate: 3860 m, straight line 2692 m; expanded 14 (Dijkstra) and 6 (A*)
   route: 30-25-17-22
Station to Old Mill: 4620 m, straight line 2365 m; expanded 29 (Dijkstra) and 10 (A*)
   route: 2-11-6-20-19-14
Output 28.2. Three routes on the town map: the same lengths, and a third to three fifths of the expansions.
The town’s places at their coordinates, from the Station (2) to the Old Mill (14). Uniform-cost search expands 29 places, shaded grey or coloured, spreading in every direction; A* expands only the 10 coloured ones, which lie towards the goal. The thick line is the route both return. Drawn by town_fig.py from the same search.
The town’s places at their coordinates, from the Station (2) to the Old Mill (14). Uniform-cost search expands 29 places, shaded grey or coloured, spreading in every direction; A* expands only the 10 coloured ones, which lie towards the goal. The thick line is the route both return. Drawn by town_fig.py from the same search.

History

Peter Hart, Nils Nilsson and Bertram Raphael published A* in 1968, with the proof that an admissible estimate keeps the answer optimal.

28.4 Two-player reachability games

Two players at a café table. In a game like this one, each move is chosen by the player whose turn it is, and the question is no longer which path exists but which outcome a player can force.
Two players at a café table. In a game like this one, each move is chosen by the player whose turn it is, and the question is no longer which path exists but which outcome a player can force.

Definition 28.9 (Reachability game, position, game graph)

A reachability game is played by two players, 00 and 11, on a directed graph, the game graph, whose vertices, the positions, each belong to one player, with a set TT of target positions. A token starts on a position; the owner of the position where the token stands moves it along an edge. Player pp wins if the token reaches TT; otherwise, including when the play goes on forever or stops at a position with no edge, player pp does not win.

Definition 28.10 (Strategy, winning strategy, winning position)

A strategy for player pp chooses a successor for each position of pp given the play so far; it is memoryless if the choice depends only on the current position. It is winning from a position if every play from there in which pp follows it reaches TT, whatever the other player does; that position is then a winning position for pp.

Definition 28.11 (Attractor)

The attractor of TT for player pp is built in layers: layer 00 is TT; a position not yet in it joins at layer i+1i + 1 if it belongs to pp and has a successor in layer ii or before, or belongs to the other player and all its successors (at least one) are in layers ≤i\leq i. The attractor is the union of the layers.

def attractor(owner, succ, target, p):
    """The positions from which p can force a visit to target, each with its layer
    (target is reached within that many moves), and a memoryless strategy for p."""
    pred = {v: [] for v in owner}
    for u in owner:
        for v in succ[u]:
            pred[v].append(u)
    left = {u: len(succ[u]) for u in owner}  # successors not yet in the attractor
    layer = {v: 0 for v in target}
    strategy, queue = {}, deque(target)
    while queue:
        v = queue.popleft()
        for u in pred[v]:
            if u in layer:
                continue
            if owner[u] == p:  # one good move is enough
                layer[u], strategy[u] = layer[v] + 1, v
                queue.append(u)
            else:
                left[u] -= 1
                if left[u] == 0:  # every move of the opponent leads in
                    layer[u] = layer[v] + 1
                    queue.append(u)
    return layer, strategy
Listing 28.5. The attractor computed backwards, with a counter of the successors left for each position of the opponent code/bachelor-2/28-search-and-games/listings/games.py

Theorem 28.12 (Attractor)

The attractor of TT for player pp is exactly the set of positions from which pp has a winning strategy. On it, the memoryless strategy that moves from each position of pp to a successor of a lower layer is winning. The listing computes the attractor and this strategy in time O(∣V∣+∣E∣)O(|V| + |E|).

Proof. From a position of layer i>0i > 0, if it belongs to pp, the strategy moves to a lower layer; if it belongs to the other player, every move leads to a lower layer. So the layer decreases at each move and the token reaches layer 00, which is TT, within ii moves.

Conversely, let uu be outside the attractor. Then u∉Tu \notin T. If uu belongs to pp, all its successors are outside, since one inside would have put uu in. If uu belongs to the other player, it has a successor outside, or no successor at all, since otherwise uu would have joined. The other player can therefore always keep the token outside the attractor: play never reaches TT, whatever pp does, and pp has no winning strategy from uu.

The listing processes each position once from the queue and looks at each edge once backwards, decrementing a counter; the running time is O(∣V∣+∣E∣)O(|V| + |E|) (Exercise 28.12). ∎

The theorem also says that memory is useless in reachability games: if pp can win at all, pp can win by looking only at the current position. In the game of matches, 21 matches lie on the table, each player takes 1, 2 or 3 in turn, and whoever takes the last match wins. A position is the number left and the player to move.

# 21 matches; a move takes 1, 2 or 3; whoever takes the last match wins. A position
# is (matches left, player to move); with no match left, the player to move has lost.
owner, succ = {}, {}
for k in range(22):
    for p in "AB":
        owner[(k, p)] = p
        other = "B" if p == "A" else "A"
        succ[(k, p)] = [(k - t, other) for t in (1, 2, 3) if t <= k]
win_a, strat = attractor(owner, succ, [(0, "B")], "A")
wins = [k for k in range(22) if (k, "A") in win_a]
print("A, to move, wins with k matches left for k =", " ".join(map(str, wins)))
print("A's winning move from 21:", f"take {21 - strat[(21, 'A')][0]};",
      "moves of both players until the end:", win_a[(21, "A")])
Listing 28.6. The game of matches as a game graph; A wins on reaching “no match left, B to move” code/bachelor-2/28-search-and-games/listings/attractor.py
$ python attractor.py
A, to move, wins with k matches left for k = 1 2 3 5 6 7 9 10 11 13 14 15 17 18 19 21
A's winning move from 21: take 1; moves of both players until the end: 11
player 0 forces e from [('a', 2), ('c', 1), ('e', 0)] strategy [('a', 'c'), ('c', 'e')]
player 1 forces h from [('b', 1), ('h', 0)]
neither: ['d', 'f', 'g']
Output 28.3. The positions won by the player to move, the first move from 21, and a small game in which some positions are won by neither.

The player to move loses exactly with a multiple of 4: whatever they take, the other takes the complement to 4. From 21, take 1. In the small game of the output, each player has a target: player 00 wants ee, player 11 wants hh. Neither can force anything from dd, ff and gg: from dd, player 11 goes to ff, and ff and gg send the token back and forth for ever. These positions are draws.

The small game of : circles belong to player 0, squares to player 1. Blue: the attractor of e for player 0, with its layers and the strategy in thick arrows. Red: the attractor of h for player 1. From the white positions neither player can force a win.
The small game of Output 28.3: circles belong to player 00, squares to player 11. Blue: the attractor of ee for player 00, with its layers and the strategy in thick arrows. Red: the attractor of hh for player 11. From the white positions neither player can force a win.

28.5 Minimax and alpha–beta

The attractor needs the whole game graph. For a game whose positions are too many, a program looks a few moves ahead and estimates the rest.

Definition 28.13 (Game tree, minimax value, evaluation function)

In a game where two players alternate, max and min, the game tree of a position has that position at its root and the positions after each move as children. The leaves carry a value for max: the result of a finished game, or the value of an evaluation function at the depth where the search stops. The minimax value of a node is its leaf value, the largest value of its children if max is to move, and the smallest if min is.

The minimax value is what max can guarantee against any play of min, and min against any play of max, in the tree as given; the move to play is towards a child of the root with the root’s value.

Definition 28.14 (Alpha–beta pruning)

Alpha–beta pruning computes the minimax value with two bounds passed down the tree: α\alpha, the value max is already sure of on the path from the root, and β\beta, the value min is already sure of. As soon as a node’s value is known to be outside (α,β)(\alpha, \beta), its remaining children are skipped: the player above has a better choice elsewhere.

def alphabeta(node, maximise, alpha, beta, count):
    """The minimax value if it lies strictly between alpha and beta; otherwise a bound
    on the same side as the true value."""
    if isinstance(node, int):
        count[0] += 1
        return node
    if maximise:
        value = -math.inf
        for c in node:
            value = max(value, alphabeta(c, False, alpha, beta, count))
            alpha = max(alpha, value)
            if alpha >= beta:
                break  # min above will never let play come here
        return value
    value = math.inf
    for c in node:
        value = min(value, alphabeta(c, True, alpha, beta, count))
        beta = min(beta, value)
        if alpha >= beta:
            break  # max above already has better
    return value
Listing 28.7. Alpha–beta, counting the leaves it evaluates code/bachelor-2/28-search-and-games/listings/alphabeta.py
$ python minimax_demo.py
values of the min nodes: [5, 2, 2]
values of the max nodes below them: [[5, 9], [2, 7], [2, 8]]
value of the root: 5
alpha-beta value: 5 | leaves evaluated: 000 001 010 100 101 200 201 (7 of 12)
Output 28.4. A tree of depth 3 with three moves at the root and two below: its minimax values, and the leaves that alpha–beta evaluates.
The tree of : triangles pointing up are  nodes, down  nodes. After the first subtree the root is sure of 5. In the second subtree,  can already force 2 < 5 after two leaves, so its second child is never looked at; the same in the third. Dashed: the 5 leaves skipped. The bounds ≥ 6 and ≤ 2 are all alpha–beta knows of those nodes.
The tree of Output 28.4: triangles pointing up are max nodes, down min nodes. After the first subtree the root is sure of 55. In the second subtree, min can already force 2<52 < 5 after two leaves, so its second child is never looked at; the same in the third. Dashed: the 5 leaves skipped. The bounds ≥6\geq 6 and ≤2\leq 2 are all alpha–beta knows of those nodes.

Theorem 28.15 (Alpha–beta)

Let vv be the minimax value of a node and rr the result of alpha–beta on it with bounds α<β\alpha < \beta. If α<v<β\alpha < v < \beta, then r=vr = v; if v≤αv \leq \alpha, then r≤αr \leq \alpha; if v≥βv \geq \beta, then r≥βr \geq \beta. In particular, with α=−∞\alpha = -\infty and β=+∞\beta = +\infty, alpha–beta returns the minimax value.

Proof. Exercise 28.10, by induction on the height of the node. ∎

How much is skipped depends on the order of the children: if the best move comes first, its value sets the tightest bound at once.

Proposition 28.16 (The best case)

On a uniform tree of branching bb and depth dd whose children are always ordered best first, alpha–beta evaluates exactly b⌈d/2⌉+b⌊d/2⌋−1b^{\lceil d/2 \rceil} + b^{\lfloor d/2 \rfloor} - 1 of the bdb^d leaves, when the leaf values are distinct.

Proof. Admitted at this level. ∎

A leaf is evaluated exactly when, along its path from the root, all the choices at the even depths are first children, or all the choices at the odd depths are; the first kind number b⌊d/2⌋b^{\lfloor d/2 \rfloor}, the second b⌈d/2⌉b^{\lceil d/2 \rceil}, and one leaf, the leftmost, is of both kinds. The characterisation is the analysis of Knuth and Moore.

$ python alphabeta.py
 b  d  leaves   alpha-beta, random order  best order  b^ceil(d/2)+b^floor(d/2)-1
 3  6     729                       155          53                           53
 4  6    4096                       917         127                          127
 4  8   65536                      7139         511                          511
 8  5   32768                      5752         575                          575
Output 28.5. Random uniform trees: all leaves, alpha–beta in random order, and alpha–beta with the children sorted best first.

With perfect ordering the count is exactly the formula, about 2bd/22b^{d/2}: in the same time, alpha–beta searches twice as deep as minimax. In random order it still skips most leaves. Real programs approach the best case by trying first the moves that were best in a shallower search.

History

John von Neumann published the theory of games of strategy, with the minimax theorem, in 1928. Donald Knuth and Ronald Moore published their analysis of alpha–beta pruning, with the best case above, in 1975.

28.6 Noughts and crosses, solved

Noughts and crosses is small enough to search completely. A position is a string of nine cells; xx moves first.

@cache
def value(b):
    """The minimax value: x maximises, o minimises."""
    ms = moves(b)
    if not ms:
        return score(b)
    best = max if to_move(b) == "x" else min
    return best(value(m) for m in ms)


def count_tree(b):
    """Nodes and leaves of the full game tree below b."""
    ms = moves(b)
    if not ms:
        return 1, 1
    nodes, leaves = 1, 0
    for m in ms:
        n, f = count_tree(m)
        nodes, leaves = nodes + n, leaves + f
    return nodes, leaves
Listing 28.8. The value of a position by minimax with memoisation, and the size of the full game tree code/bachelor-2/28-search-and-games/listings/tictactoe.py
$ python tictactoe.py
value of the empty board: 0
distinct positions reachable: 5478
game tree: 549946 nodes, 255168 finished games
x in the centre, then o in a corner: 0 | o on an edge: 1
Output 28.6. The game solved: a draw with best play.

The full tree has 549,946 nodes, but only 5,478 distinct positions: the same position is reached by many orders of the same moves, and the memo computes each once. The value 00 says that neither player can force a win: the game is a draw if both play well. The last line shows a mistake that loses: after a cross in the centre, a nought on an edge lets the crosses force a win. With the eight symmetries of the square the positions drop to 765 (Exercise 28.11).

28.7 Exercises

Exercise 28.1 ★

Run breadth-first search on the town’s roads from the Bus Depot by hand, taking the neighbours of each place in the order of the road table, and list the places by depth. Check with exo_bfs_order.py.

Solution

Solution of Exercise 28.1.

The queue starts with the Bus Depot (16). Its roads lead to 4, 7 and 24, in that order, which form depth 1. Expanding 4 adds 15; 7 adds 23; 24 adds 1 and 3: depth 2. The process goes on until every place is reached, at depth 6 at most.

$ python exo_bfs_order.py
depth 0: [16]
depth 1: [4, 7, 24]
depth 2: [15, 23, 1, 3]
depth 3: [14, 19, 20, 10, 26]
depth 4: [5, 6, 13, 2, 9, 21]
depth 5: [11, 12, 17, 28, 18]
depth 6: [8, 30, 22, 25, 27, 29]
Output 28.8. The places by depth from the Bus Depot, in the order they leave the queue.

Exercise 28.2 ★

Use three times the straight-line distance as the heuristic of A* on the town map. Find a pair of places for which the route returned is longer than the shortest one, and explain which step of the proof of Theorem 28.8 fails. Check with exo_inadmissible.py.

Solution

Solution of Exercise 28.2.

From the Bus Depot to the Bakery Corner, A* with three times the straight line returns a route of 4,800 m, while the shortest is 4,360 m. On the other two pairs it is lucky, and it expands fewer states every time.

$ python exo_inadmissible.py
Station to Old Mill, h = 1 x straight line: 4620 m, 10 expanded, route 2-11-6-20-19-14
Station to Old Mill, h = 3 x straight line: 4620 m, 7 expanded, route 2-11-6-20-19-14
Lighthouse Café to West Gate, h = 1 x straight line: 3860 m, 6 expanded, route 30-25-17-22
Lighthouse Café to West Gate, h = 3 x straight line: 3860 m, 4 expanded, route 30-25-17-22
Bus Depot to Bakery Corner, h = 1 x straight line: 4360 m, 6 expanded, route 16-4-15-20-13
Bus Depot to Bakery Corner, h = 3 x straight line: 4800 m, 5 expanded, route 16-7-15-20-13
Output 28.9. An overestimate expands fewer states and can return a longer route.

In the proof, the new cost c′=c−h(s)+h(t)c' = c - h(s) + h(t) was non-negative because hh was consistent. With hh three times the straight line, a road of length cc towards the goal can lower hh by up to 3c3c, so c′c' can be negative, and the argument of uniform-cost search, which needs non-negative costs, breaks. The heuristic is not even admissible: at North School h=3×2 971=8 914h = 3 \times 2\,971 = 8\,914 m against a true 3 6203\,620 m, so its priority, 740+8 914=9 654740 + 8\,914 = 9\,654 m, is above the Swimming Pool’s 1 770+7 717=9 4871\,770 + 7\,717 = 9\,487 m. The Swimming Pool is expanded first, the Football Ground is reached and closed through it with g=2 870g = 2\,870 m instead of 2 4302\,430 m, 440 m too long, and the listing never reopens it.

Exercise 28.3 ★

Compare iterative deepening with breadth-first search on scrambled 8-puzzles: states expanded, and states kept in memory. Use exo_iddfs.py.

Solution

Solution of Exercise 28.3.

$ python exo_iddfs.py
depth  4: BFS expands    29, iterative deepening     53; IDDFS keeps a path of 5 states
depth 10: BFS expands   605, iterative deepening   1705; IDDFS keeps a path of 11 states
depth 20: BFS expands 37899, iterative deepening 280582; IDDFS keeps a path of 21 states
Output 28.10. Iterative deepening expands more states, but keeps only one path.

Breadth-first search keeps every state it has generated, tens of thousands at depth 20; iterative deepening keeps a path of d+1d + 1 states. It expands more than the ratio b/(b−1)b/(b - 1) of Exercise 28.4 suggests, seven times more at depth 20, because the 8-puzzle’s state space is a graph, not a tree: depth-first search reaches the same state by many paths and expands it each time, while breadth-first search expands it once. Iterative deepening trades time for memory.

Exercise 28.4 ★

A tree in which every node has b≥2b \geq 2 children has (bd+1−1)/(b−1)(b^{d+1} - 1)/(b - 1) nodes down to depth dd. Prove it, and deduce that iterative deepening expands at most b/(b−1)b/(b - 1) times as many nodes as one depth-limited search to depth dd, counting nodes with repetition.

Solution

Solution of Exercise 28.4.

There are bkb^k nodes at depth kk, so 1+b+⋯+bd=(bd+1−1)/(b−1)1 + b + \dots + b^d = (b^{d+1} - 1)/(b - 1) down to depth dd, by the sum of a geometric series. Iterative deepening runs the searches to depths 0,…,d0, \dots, d, so it expands

∑k=0dbk+1−1b−1≤1b−1∑k=0dbk+1=bb−1⋅bd+1−1b−1\sum_{k=0}^{d} \frac{b^{k+1} - 1}{b - 1} \leq \frac{1}{b - 1} \sum_{k=0}^{d} b^{k+1} = \frac{b}{b - 1} \cdot \frac{b^{d+1} - 1}{b - 1}

nodes, which is b/(b−1)b/(b - 1) times the count of the last search alone: at most twice for b=2b = 2, about 1.11.1 times for b=10b = 10.

Exercise 28.5 ★★

Compute the minimax value of the tree [[[4, 8, 2], [7, 1]], [[3], [9, 6], [5, 0]], [[6, 2], [1, 3, 8]]] with min to move at the root, and then with max. Check with exo_minimax.py.

Solution

Solution of Exercise 28.5.

With min at the root, the second level is max and the third min. The children are

max⁡(min⁡(4,8,2),min⁡(7,1))=max⁡(2,1)=2,max⁡(3,6,0)=6,max⁡(2,1)=2,\max(\min(4, 8, 2), \min(7, 1)) = \max(2, 1) = 2, \quad \max(3, 6, 0) = 6, \quad \max(2, 1) = 2,

and the root is min⁡(2,6,2)=2\min(2, 6, 2) = 2. With max at the root, the children are min⁡(8,7)=7\min(8, 7) = 7, min⁡(3,9,5)=3\min(3, 9, 5) = 3 and min⁡(6,8)=6\min(6, 8) = 6, and the root is 77.

$ python exo_minimax.py
min at the root: 2 | max at the root: 7
Output 28.11. The two values.

Exercise 28.6 ★★

The function ab_short of exo_ab_bug.py starts every node with α=−∞\alpha = -\infty and β=+∞\beta = +\infty instead of receiving them from its parent. Is its value right? How many leaves does it evaluate, and why?

Solution

Solution of Exercise 28.6.

$ python exo_ab_bug.py
minimax     : value 297, 729 leaves
alpha-beta  : value 297, 321 leaves
fresh bounds: value 297, 729 leaves
Output 28.12. Without inherited bounds, nothing is pruned.

The value is right, but all 729 leaves are evaluated. In a max node with fresh bounds, β\beta stays +∞+\infty, so α≥β\alpha \geq \beta never holds; in a min node, α\alpha stays −∞-\infty. The function is minimax with a test that never fires. A cut-off happens when a node’s value falls outside a bound set by an ancestor: the bounds must come from above.

Exercise 28.7 ★★

In the subtraction game, a move takes 1, 3 or 4 matches, and whoever takes the last wins. Compute the attractor for the first player from up to 30 matches, guess the losing positions, and prove your guess.

Solution

Solution of Exercise 28.7.

$ python exo_subtraction.py
the player to move loses with k = [0, 2, 7, 9, 14, 16, 21, 23, 28, 30]
k mod 7 of these: [0, 2]
Output 28.13. The losing positions up to 30.

Claim: the player to move loses exactly when k≡0k \equiv 0 or 2(mod7)2 \pmod 7. By strong induction on kk. With k≡0k \equiv 0, the moves lead to residues 66, 44 and 33; with k≡2k \equiv 2, to 11, 66 and 55: never to a losing residue, so by induction the opponent wins. From the other residues there is a move to a losing one: from 11 take 1, from 33 take 1, from 44 take 4, from 55 take 3, from 66 take 4; in each case the move is possible, since kk is at least that residue. So these positions are won.

Exercise 28.8 ★★

Prove Proposition 28.6.

Solution

Solution of Exercise 28.8.

Let s=s0,s1,…,sns = s_0, s_1, \dots, s_n be an optimal path to a goal sns_n, with costs c1,…,cnc_1, \dots, c_n. Consistency gives h(si−1)≤ci+h(si)h(s_{i-1}) \leq c_i + h(s_i) for each ii. Adding these inequalities, the terms h(s1),…,h(sn−1)h(s_1), \dots, h(s_{n-1}) cancel and h(s)≤c1+⋯+cn+h(sn)=h∗(s)h(s) \leq c_1 + \dots + c_n + h(s_n) = h^*(s), since h=0h = 0 on goals. If no goal is reachable, h∗(s)=∞h^*(s) = \infty and there is nothing to prove.

Exercise 28.9 ★★

Prove that the Manhattan distance of the 8-puzzle is consistent, and that it is never smaller than the number of misplaced tiles. Then compute the true distance of all 181,440 states by one breadth-first search backwards from the goal, and check both heuristics against it.

Solution

Solution of Exercise 28.9.

A move slides one tile by one cell, so it changes that tile’s distance to its place by exactly 11 and leaves the others unchanged: the Manhattan distance changes by ±1\pm 1 for a move of cost 11, hence h(s)≤1+h(t)h(s) \leq 1 + h(t). Each misplaced tile is at least one cell from its place, so the Manhattan distance is at least the number of misplaced tiles. By Proposition 28.6 both are admissible.

$ python exo_manhattan.py
181440 states reachable; largest distance 31
misplaced: above the true distance 0 times, equal 79 times; mean gap 14.86
manhattan: above the true distance 0 times, equal 2351 times; mean gap 7.97
Output 28.14. Both heuristics against the true distances of all reachable states.

Neither heuristic ever exceeds the true distance. The Manhattan distance is exact on 2,351 states and falls short by about 8 moves on average, against about 15 for the misplaced tiles: that gap is what Output 28.1 measures.

Exercise 28.10 ★★★

Prove Theorem 28.15.

Solution

Solution of Exercise 28.10.

Write [x]=min⁡(max⁡(x,α),β)[x] = \min(\max(x, \alpha), \beta) for xx clamped to [α,β][\alpha, \beta]. The three cases of the theorem say exactly [r]=[v][r] = [v]: if α<v<β\alpha < v < \beta, then [r]=v[r] = v forces r=vr = v; if v≤αv \leq \alpha, [r]=α[r] = \alpha means r≤αr \leq \alpha; if v≥βv \geq \beta, [r]=β[r] = \beta means r≥βr \geq \beta.

Induction on the height. At a leaf, r=vr = v. Take a max node with children of values v1,…,vkv_1, \dots, v_k, and let mj=max⁡(v1,…,vj)m_j = \max(v_1, \dots, v_j) and μj\mu_j the variable value after child jj, with m0=μ0=−∞m_0 = \mu_0 = -\infty. We show [μj]=[mj][\mu_j] = [m_j] for each jj that the loop reaches. It holds for j=0j = 0. Suppose it holds for j−1j - 1 and the loop goes on, so μj−1<β\mu_{j-1} < \beta. Then mj−1<βm_{j-1} < \beta too, and both clamps equal αj=max⁡(α,μj−1)=max⁡(α,mj−1)\alpha_j = \max(\alpha, \mu_{j-1}) = \max(\alpha, m_{j-1}), which is the lower bound passed to child jj. For any m<βm < \beta and any xx, a check of the three cases for xx (below αm\alpha_m, between αm\alpha_m and β\beta, above β\beta) gives [max⁡(m,x)]=min⁡(max⁡(x,αm),β)[\max(m, x)] = \min(\max(x, \alpha_m), \beta) with αm=max⁡(α,m)\alpha_m = \max(\alpha, m). Applying it with m=μj−1m = \mu_{j-1}, x=rjx = r_j, and with m=mj−1m = m_{j-1}, x=vjx = v_j, and using the induction hypothesis on child jj with bounds (αj,β)(\alpha_j, \beta), gives [μj]=[mj][\mu_j] = [m_j].

If the loop stops after child jj because μj≥β\mu_j \geq \beta, then [mj]=[μj]=β[m_j] = [\mu_j] = \beta, so mj≥βm_j \geq \beta and v=mk≥mj≥βv = m_k \geq m_j \geq \beta: [v]=β=[μj][v] = \beta = [\mu_j]. Otherwise the loop ends at j=kj = k with [μk]=[mk]=[v][\mu_k] = [m_k] = [v]. min nodes are symmetric, exchanging the roles of α\alpha and β\beta and of max⁡\max and min⁡\min.

Exercise 28.11 ★★★

Count the positions of noughts and crosses reachable from the empty board, then count them up to the rotations and reflections of the square, keeping one representative of each class.

Solution

Solution of Exercise 28.11.

$ python exo_symmetry.py
positions reachable: 5478; up to symmetry: 765
Output 28.15. The positions, and their classes under the eight symmetries.

A depth-first walk from the empty board collects the 5,478 reachable positions. For each, the program computes its eight images under the four rotations and their mirror images, and keeps the smallest string as the representative of its class: two positions are in the same class exactly when they have the same representative. There are 765 classes. A search with memoisation keyed on the representative computes each value once per class.

Exercise 28.12 ★★★

Prove that Listing 28.5 runs in time O(∣V∣+∣E∣)O(|V| + |E|), and that a position of the opponent enters the attractor exactly when its counter reaches 00.

Solution

Solution of Exercise 28.12.

Building the predecessor lists costs O(∣V∣+∣E∣)O(|V| + |E|). A position is put in the queue only when it receives a layer, and never again, since positions with a layer are skipped; so each position leaves the queue at most once, and when vv leaves it, its predecessor list is walked once. Each edge (u,v)(u, v) is therefore looked at once, at constant cost: the loop costs O(∣V∣+∣E∣)O(|V| + |E|) in all.

The counter of a position uu of the opponent starts at its number of successors, counted with repetition. It is decremented once for each edge (u,v)(u, v) when vv leaves the queue, that is once for each successor entering the attractor. It reaches 00 exactly when all successors are in the attractor, which is the condition of the definition; with a counter instead of a check of all successors, the time stays linear.

28.8 Problem: The delivery robot and its rival

Problem 28.1

Weekend problem — The delivery robot and its rival

A delivery robot leaves the Bus Depot with parcels for the Library (place 3), the Museum (12) and the Hospital (8), in any order. Then a rival robot tries to catch it on its way to the Library. Last, the robots play noughts and crosses.

# Part I-II: start at the Bus Depot, deliver to the Library, the Museum and the
# Hospital in any order. A state is (place, deliveries still to make).
DEPOT, STOPS = 16, frozenset({3, 12, 8})


def successors(state):
    place, todo = state
    for nxt, d in ROADS.get(place, []):
        yield (nxt, todo - {nxt}), d


def h(state):  # the farthest stop left, in a straight line: admissible
    place, todo = state
    return max((straight(place, s) for s in todo), default=0)


start = (DEPOT, STOPS)
for name, heur in [("uniform cost", lambda s: 0), ("A*, farthest stop", h)]:
    path, cost, expanded = astar(start, lambda s: not s[1], successors, heur)
    print(f"{name:17}: {cost} m, {expanded} states expanded;",
          "route", "-".join(str(p) for p, _ in path))
Listing 28.9. The deliveries as a search problem: a state is a place and the deliveries left code/bachelor-2/28-search-and-games/listings/robot_problem.py
$ python robot_problem.py
uniform cost     : 11980 m, 114 states expanded; route 16-24-3-24-16-4-15-20-6-12-8
A*, farthest stop: 11980 m, 56 states expanded; route 16-24-3-24-16-4-15-20-6-12-8
1800 positions: robot wins from 784, rival from 202, neither from 814
robot at Bus Depot, rival at Station: robot wins, first move to South Bridge, 3 moves in all
robot at Bus Depot, rival at Town Square: neither wins
robot at Allotments, rival at Town Hall: rival wins after 8 moves in all
noughts and crosses: alpha-beta value 0 after 7330 finished games of 255168
Output 28.7. The best delivery round, the race game solved, and alpha–beta on noughts and crosses.

Part I — The state space.

  1. How many states does the delivery problem have? Which are goals?
  2. Why must the state contain the deliveries left, and not only the place?
  3. Why does the route of Output 28.7 go through the South Bridge twice? Is that allowed in the state space?
  4. How many actions does a state have, and what do they cost?
  5. Would breadth-first search find the same route? Run it, and say why the answer is luck.
  6. With kk stops instead of 3, how does the number of states grow?

Part II — A* on the town.

  1. Prove that hh, the straight-line distance to the farthest stop left, is admissible.
  2. Prove that it is consistent.
  3. Would the sum of the straight-line distances to the stops left be admissible? Give a counterexample or a proof.
  4. A* expands 56 states and uniform-cost search 114. Explain where the saving comes from.
  5. Propose a better admissible heuristic, and say why it is admissible.
  6. How would A* change if the robot had to return to the depot at the end?

Part III — The race, solved backwards.

  1. Positions are (robot’s place, rival’s place, player to move). Check that there are 1,800.
  2. Which positions form the robot’s target, and which the rival’s? Why do they get a loop?
  3. From the Bus Depot, with the rival at the Station, the robot wins in 3 moves. Describe the play.
  4. From the Bus Depot with the rival at the Town Square, neither wins. What do the robots do for ever?
  5. From the Allotments, with the rival at the Town Hall, the rival wins. Why can it never be a draw there?
  6. The robot wins from 784 positions and the rival from 202. Why is the game not symmetric?

Part IV — Alpha–beta measured.

  1. On the random tree with b=4b = 4 and d=8d = 8, compare the leaves evaluated in random order and best first with 484^8 and with the formula of Proposition 28.16.
  2. In the same time, how much deeper does alpha–beta with perfect ordering search than minimax?
  3. On noughts and crosses, alpha–beta finishes 7,330 of the 255,168 games. Why is the saving larger than on the random trees?
  4. Why does alpha–beta call the game with α=−2\alpha = -2 and β=2\beta = 2 rather than infinite bounds?
  5. How should a program order the moves of noughts and crosses to approach the best case?
  6. State the problem’s result: alpha–beta with good ordering visits LL of NN leaves, near the bd/2b^{d/2} bound, with the values of LL and NN measured here.
Solution

Solution of Problem 28.1.

1. A state is a place and a subset of the three stops: 30×23=24030 \times 2^3 = 240 states. The goals are the 30 states with no delivery left.

2. The same place means different things before and after a delivery: the round from the Library back past the South Bridge would be a cycle if the state were the place alone, and the goal test, “all parcels delivered”, could not be read from it.

3. Only two roads leave the Library, to the South Bridge and to the Garden Centre, and the shortest way on to the Museum goes back over the South Bridge. The states (24,{3,8,12})(24, \{3, 8, 12\}) and (24,{8,12})(24, \{8, 12\}) are different, so the route is a simple path in the state space.

4. One action per road leaving the place, with one-way roads only in their direction; its cost is the road’s length. The deliveries left lose the new place if it is a stop.

5. Here it does: breadth-first search on the same state space returns the same round, 10 roads and 11 980 m. That is luck: breadth-first search minimises the number of roads, not the metres, and on another map the round of fewest roads may be longer.

6. 30⋅2k30 \cdot 2^k: exponential in the number of stops, as for the travelling salesman problem.

7. Any route that delivers the stops left visits the farthest one, ss, so its length is at least the road distance to ss, which is at least the straight line, since no road is shorter than the straight line between its ends. On goals h=0h = 0.

8. Take an action from (u,S)(u, S) to (v,S′)(v, S') along a road of length d≥∥u−v∥d \geq \lVert u - v \rVert. For s∈Ss \in S: if s=vs = v, then ∥u−s∥≤d\lVert u - s \rVert \leq d; otherwise s∈S′s \in S' and ∥u−s∥≤d+∥v−s∥≤d+h(v,S′)\lVert u - s \rVert \leq d + \lVert v - s \rVert \leq d + h(v, S'). Taking the maximum over ss, h(u,S)≤d+h(v,S′)h(u, S) \leq d + h(v, S').

9. No. With stops 1 km and 2 km away along a straight road, the round costs 2 km and the sum is 3 km.

10. A* never expands a state with g+hg + h above 11,980 m, the optimal cost; uniform-cost search expands every state with gg below it, including those that head away from the remaining stops.

11. The length of a minimum spanning tree, in straight lines, of the current place and the stops left. Any round from the place through all the stops, shortened to straight lines between the points it visits in order, is a spanning path, so at least as long as the minimum spanning tree: the heuristic is admissible. It is at least the old hh, since the tree contains a path to the farthest stop.

12. The goal becomes (16,∅)(16, \varnothing), and a natural admissible heuristic is the maximum over the stops left of the straight line to the stop plus the straight line from it to the depot, or the straight line to the depot when no stop is left.

13. The robot has 30 places, the rival 30, and the turn two values: 30⋅30⋅2=1,80030 \cdot 30 \cdot 2 = 1{,}800.

14. The robot’s target is the positions with the robot at the Library and the rival elsewhere; the rival’s, those with both robots on the same place. The play stops there, and the loop gives each such position a successor, so that the definition of the attractor, which asks about all successors, applies everywhere.

15. The robot moves to the South Bridge. The rival, at the Station, can reach only the Town Hall, the River Park and the Hill Park, none of which is the South Bridge or the Library. The robot then moves to the Library: three moves in all.

16. On foot every road is two-way, so the Library has three neighbours: the South Bridge, the Garden Centre and the Town Square itself. A rival at the Town Square is next to the Library and to both other places next to it, so it answers any step of the robot onto one of the three by a capture, and the robot keeps away. The position is in neither attractor: by the proof of Theorem 28.12, the rival can keep the token out of the robot’s attractor and the robot can keep it out of the rival’s, so the robots circle for ever, the rival guarding the Library and the robot keeping out of reach.

17. The position is in the rival’s attractor, at layer 8: by Theorem 28.12 the rival has a strategy that catches the robot within 8 moves, whatever the robot does. A position in an attractor is won, so it is never a draw.

18. The targets differ: the robot must reach one fixed place, the rival must meet a moving robot. Moreover the robot is caught whenever the two share a place, whoever moved last.

19. Of the 48=65,5364^8 = 65{,}536 leaves, alpha–beta evaluates 7,139 in random order, about 11 %, and 511 when the children are best first, exactly 44+44−14^4 + 4^4 - 1.

20. The best case is about 2bd/22b^{d/2} leaves. In the time minimax takes to search to depth dd, about bdb^d leaves, alpha–beta searches to about 2d2d: twice as deep.

21. The values are only −1-1, 00 and 11, and most are draws: as soon as a player is sure of 00 and the other finds 00, the test α≥β\alpha \geq \beta holds and the rest is cut. Many games also end before the board is full, so the tree is far from uniform.

22. All values lie in [−1,1][-1, 1], so −2-2 and 22 act as infinite bounds: by Theorem 28.15 the value returned is exact, and the program stays in integers.

23. Try first a move that wins at once, then one that blocks the opponent’s line, then the centre, the corners and the edges; or the moves that were best in a shallower search, or best according to the memo.

24. On the random tree with b=4b = 4 and d=8d = 8, alpha–beta with perfect ordering visits L=511L = 511 of N=65,536N = 65{,}536 leaves, exactly the bound b⌈d/2⌉+b⌊d/2⌋−1b^{\lceil d/2 \rceil} + b^{\lfloor d/2 \rfloor} - 1; on noughts and crosses, it finishes 7,330 of the 255,168 games.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো