Problem Set 19: Modeling a Simple System – Part 1

When you start a new problem set, your first instinct might be to open your computer and begin typing code right away. While this can feel productive, it often leads to frustration when things don't work as expected. Instead, take a few minutes to slow down and plan.

Here are some helpful strategies:

  1. Understand the problem clearly
    • Read the instructions carefully — twice if needed.
    • Ask yourself: What exactly is being asked?
  2. Break the problem into smaller steps
    • Think about the smallest possible actions the computer will need to perform.
    • For example: If the task is to find the first recurring letter in a word, what steps must happen first?
  3. Try solving it on paper first
    • Write out your steps in plain language (pseudocode).
    • Test your steps with a simple example before touching the keyboard.
  4. Translate your steps into code
    • Start small — write only a few lines at a time and test often.
    • Don't worry about perfection at first; get a working version, then improve it.
  5. Check your solution
    • Run it with different examples, including edge cases.
    • Ask: Does this solve the problem in all situations?

  • Read the question carefully (twice).
  • Break the task into the smallest steps.
  • Sketch or write pseudocode before coding.
  • Start small — test as you go.
  • Check your solution with different cases.

Create a Basic Ant Model


Introduction – The Story

Ants are tiny creatures, but together they form complex societies. In this problem set, you will model a single ant moving around a simple 2D grid.

Why?

  • To see how simple rules can create interesting behavior.
  • To prepare for Part 2, where multiple ants interact (colony behavior).

In real life, computer scientists use similar models to study traffic flow, crowd dynamics, disease spread, and swarm robotics.


The Problem

You need to simulate a single ant moving on a 2D grid.

Rules for the ant:

  1. The grid is a square of size n x n.
  2. The ant starts in the center.
  3. The ant can face one of four directions: North, East, South, West.
  4. Each step, the ant chooses a random direction (turn left, turn right, or keep going straight).
  5. The ant moves one cell in that direction.
  6. The grid keeps track of where the ant has been (visited cells).

Your Goal: Write a simulation of the ant’s movement for steps turns and return:

  • The final position of the ant.
  • The number of unique cells visited.

Learning Objectives (IB Command Terms)

  • Define: grid, state, and rule in a simulation.
  • Describe: how randomness can influence a system.
  • Construct: a Python simulation of an ant.
  • Trace: the movement of an ant over multiple steps.

Starter Code

import random

class Ant:
    def __init__(self, grid_size: int):
        self.grid_size = grid_size
        self.x = grid_size // 2   # start in center
        self.y = grid_size // 2
        self.direction = "N"      # start facing North
        self.visited = {(self.x, self.y)}  # set of visited positions

    def turn(self):
        """Randomly turn left, right, or continue straight"""
        directions = ["N", "E", "S", "W"]
        idx = directions.index(self.direction)
        move = random.choice(["L", "R", "S"])
        if move == "L":
            self.direction = directions[(idx - 1) % 4]
        elif move == "R":
            self.direction = directions[(idx + 1) % 4]
        # 'S' = keep going straight

    def move(self):
        """Move one step forward in the current direction"""
        if self.direction == "N":
            self.y = max(0, self.y - 1)
        elif self.direction == "S":
            self.y = min(self.grid_size - 1, self.y + 1)
        elif self.direction == "E":
            self.x = min(self.grid_size - 1, self.x + 1)
        elif self.direction == "W":
            self.x = max(0, self.x - 1)
        self.visited.add((self.x, self.y))

    def step(self):
        """One step = choose turn + move"""
        self.turn()
        self.move()


def simulate_ant(grid_size: int, steps: int):
    ant = Ant(grid_size)
    for _ in range(steps):
        ant.step()
    return (ant.x, ant.y), len(ant.visited)

Test Cases

from ant import simulate_ant

# Run 10 steps on a 5x5 grid
print(simulate_ant(5, 10))
# Example output: ((3, 1), 7)  → final position may vary (randomness!)

# Zero steps
print(simulate_ant(5, 0))
# Expected: ((2, 2), 1) → only center cell visited

# Larger grid, more steps
print(simulate_ant(20, 100))
# Output will vary, but visited count should be between 1 and 100

Student Tasks

  1. Run the starter code and observe the random paths.
  2. Trace a few steps by printing the ant’s position after each move.
  3. Modify the rules:
    • What if the ant always turns left?
    • What if the ant only moves North/South?
  4. Visualize the path (e.g., print the grid with . for empty, * for visited).
  5. Write a reflection: How do simple rules lead to complex-looking patterns?