Problem 5

Simulate the wolf fleeing a city.

A city is given as a grid of n x n crossroads. At each crossroad, the wolf picks a random direction. The grid size n is greater than 1 and odd.

The wolf starts at (0, 0). The wolf escaped the city when he reaches the border of the grid.

The wolf can never visit the same crossroad twice. If there are no more options, the wolf is shot by the hunters and dies.

Estimate the probability of the wolf escaping the city.

(We deliberately exclude the parts of the exercise concerning the drawing of the paths in the GUI.)

Classes:

Position(x, y)

Represent the current position of the wolf on the grid.

Functions:

list_next_positions(pos)

List all the possible next positions based on the current position pos.

simulate(trials, grid_size)

Simulate trials` number of wolf journeys on the quadratic ``grid_size grid.

class Position(x: int, y: int)[source]

Represent the current position of the wolf on the grid.

Methods:

__init__(x, y)

Initialize with the given values.

__repr__()

Represent the instance as a string for debugging.

Attributes:

x

X-coordinate of the cell

y

Y-coordinate of the cell

__init__(x: int, y: int) None[source]

Initialize with the given values.

x: Final[int]

X-coordinate of the cell

y: Final[int]

Y-coordinate of the cell

__repr__() str[source]

Represent the instance as a string for debugging.

list_next_positions(pos: Position) Sequence[Position][source]

List all the possible next positions based on the current position pos.

Ensures
  • all(
        (next_pos.x == pos.x and next_pos.y != pos.y)
        ^ (next_pos.x != pos.x and next_pos.y == pos.y)
        for next_pos in result
    )
    

    (Next is either in x- or in y-direction)

  • all(
        not (next_pos.y != pos.y) or (abs(next_pos.y - pos.y) == 1)
        for next_pos in result
    )
    

    (Next is at most 1 field in y-direction)

  • all(
        not (next_pos.x != pos.x) or (abs(next_pos.x - pos.x) == 1)
        for next_pos in result
    )
    

    (Next is at most 1 field in x-direction)

  • pos not in result

  • len(result) == 4

simulate(trials: int, grid_size: int) float[source]

Simulate trials` number of wolf journeys on the quadratic ``grid_size grid.

Requires
  • grid_size % 2 == 1

  • grid_size > 1

  • trials > 0

Ensures
  • 0 <= result <= 1