Tutorial outline

Unit 1

  1. 01Getting started
  2. 02Names and functions
  3. 03Control
  4. 04Higher-order functions
  5. 05Environments and closures
  6. 06Functional abstraction
  7. 07Recursion
  8. 08Tree recursion
  1. D0Getting started
  2. D1Control and environment diagrams
  3. HW1Functions and control
  4. D2Higher-order functions
  5. HW2Higher-order functions
  6. P1Hog
  7. D3Recursion
  8. D4Tree recursion
  9. HW3Recursion

Unit 2

  1. 09Sequences
  2. 10Dictionaries, sets, and tuples
  3. 11Optionals
  4. 12Structures and enumerations
  5. 13Linked lists and trees
  6. 14Mutation and value semantics
  7. 15Classes and inheritance
  8. 16Protocols and generics
  9. 17Iterators and lazy sequences
  10. 18Efficiency and memoization
  1. HW4Sequences and containers
  2. P2Cats
  3. D5Trees
  4. HW5Recursive data and mutation
  5. D6Objects and classes
  6. HW6Classes and interfaces
  7. P3Ants vs. SomeBees
  8. D7Iterators and efficiency
  9. HW7Lazy sequences and efficiency

Unit 3

  1. 19Algebraic data types and pattern matching
  2. 20Writing an interpreter
  3. 21Error handling
  4. 22Concurrency with async and await
  5. 23Testing
  6. 24Building a Swift package
  1. D8Algebraic data types
  2. HW8Pattern matching
  3. D9Interpreters
  4. HW9Interpreters and errors
  5. P4Scheme
  6. D10Concurrency
  7. D11Testing
  8. HW10Concurrency and testing

Unit 4

  1. 25References, identity, and memory
  2. 26Drawing with SwiftUI
  3. 27Testing data structures
  4. 28IntLists and SLLists
  5. 29Doubly linked lists and deques
  6. 30Arrays from scratch
  7. 31Interface and implementation inheritance
  8. 32Iteration, equality, and ordering
  9. 33Copy-on-write collections
  1. D12Swift review
  2. D13References, classes, and arrays
  3. HW11Swift warm-up
  4. P5Particle Simulator
  5. D14IntLists and SLLists
  6. HW12IntLists
  7. P6LinkedListDeque
  8. D15DLLists, default implementations, and array lists
  9. P7ArrayDeque
  10. D16Comparables and iterators
  11. HW13Review I

Unit 5

  1. 34Asymptotic analysis
  2. 35Disjoint sets
  3. 36Analyzing recursion
  4. 37Amortized analysis and the limits of big O
  5. 38Sets, maps, and binary search trees
  6. 39B-trees
  7. 40Left-leaning red-black trees
  8. 41Heaps and priority queues
  1. D17Asymptotics and disjoint sets
  2. P8Percolation
  3. D18Asymptotics II
  4. HW14Asymptotic analysis
  5. D19BSTs, B-trees, and LLRBs
  6. HW15BSTMap

Unit 6

  1. 42Data-driven apps with SwiftUI
  2. 43Tree and graph traversals
  3. 44Graph implementations
  4. 45Shortest paths: Dijkstra and A*
  5. 46Minimum spanning trees
  6. 47DAGs, topological sort, and reductions
  1. D20Tree traversals and graphs
  2. P9NGordNet
  3. D21Shortest paths and MSTs

Unit 7

  1. 48Hash tables
  2. 49Hash functions
  3. 50Tries and prefix operations
  4. 51Software engineering: managing complexity
  5. 52Games with SwiftUI
  6. 53Designing a world
  7. 54Basic sorts
  8. 55Quicksort and selection
  9. 56The limits of sorting
  10. 57Radix sorts
  11. 58Compression and complexity
  12. 59Computing, society, and what comes next
  1. D22Hashing and tries
  2. HW16Review II
  3. D23Hashing and tries, revisited
  4. P10Build Your Own World
  5. D24Sorting
  6. HW17HashMap
  7. D25Sorting II
  8. HW18LLRB set
  9. HW19Final review

Designing a world

Planning a program too big to hold in your head, through Project 10: pseudorandom generation from a seed, rooms and hallways, guaranteeing connectivity with graph algorithms, walls from floors, and a module design with testable properties.

CS61B
Software Engineering II · BYOW Warmup · Textbook Ch. 28
Swift book
Functions

Project 10, Build Your Own World, asks for a program that generates a random world of rooms and hallways from a number, lets a player explore it, and saves and loads games. CS61B spends a lecture on how to start such a project, and so does this lesson. It works through the hardest part, generating a good world, and uses it to practice Lesson 51’s ideas: deciding modules and interfaces before writing code.

Randomness you can repeat

The world must be random, so that each seed gives a different, interesting world, and repeatable, so that the same seed always gives the same world (Lesson 52’s replay requirement). Both come from a pseudorandom number generator: a deterministic function that turns a seed into a long sequence of numbers that look random. Swift’s SystemRandomNumberGenerator is not seedable, so the project uses its own, conforming to RandomNumberGenerator, which every standard random API accepts:

struct SplitMix64: RandomNumberGenerator {
    private var state: UInt64

    init(seed: UInt64) {
        state = seed
    }

    mutating func next() -> UInt64 {
        state &+= 0x9E3779B97F4A7C15
        var z = state
        z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9
        z = (z ^ (z >> 27)) &* 0x94D049BB133111EB
        return z ^ (z >> 31)
    }
}

var a = SplitMix64(seed: 42)
var b = SplitMix64(seed: 42)
let first = (0..<5).map { _ in Int.random(in: 1...6, using: &a) }
let second = (0..<5).map { _ in Int.random(in: 1...6, using: &b) }
print(first == second, [1, 2, 3, 4].shuffled(using: &a).count)   // true 4

This is the SplitMix64 algorithm, which Lesson 23 used for property tests. Its overflow operators (&+=, &*) wrap around by design. Two rules keep a world repeatable:

  • Every random choice uses the one seeded generator, passed along as inout. A single call to Int.random(in:) without using: makes worlds differ between runs.
  • The generator is used in the same order every time. Iterating over a Set or Dictionary to make random choices breaks this, since their order changes between runs (Lesson 49). Sort first.

Rooms and hallways

A classic approach, and the one CS61B suggests, has three steps:

  1. Place rooms. Try random rectangles; keep each one that does not overlap (or touch) a room already placed; stop after enough rooms or attempts.
  2. Connect them. Join rooms with hallways, one tile wide, bending at most once (an L shape), so that every room can be reached from every other.
  3. Add walls. Every empty tile next to a floor tile becomes a wall.

Step 2 is where the algorithms of this course pay off. Connecting each room to the next one in the order they were placed works, but makes long winding paths. Better: treat rooms as vertices, distances between their centers as edge weights, and connect them along a minimum spanning tree (Lesson 46), which connects everything with the least total hallway. A few extra random hallways then add loops, so the world is not a tree.

struct Room {
    let x: Int, y: Int, width: Int, height: Int
    var center: (x: Int, y: Int) { (x + width / 2, y + height / 2) }

    func overlaps(_ other: Room) -> Bool {
        x <= other.x + other.width && other.x <= x + width &&
        y <= other.y + other.height && other.y <= y + height
    }
}

/// Indices of room pairs to connect: a minimum spanning tree by Kruskal’s algorithm.
func hallwayPairs(_ rooms: [Room]) -> [(Int, Int)] {
    var pairs: [(Int, Int, Int)] = []
    for i in rooms.indices {
        for j in rooms.indices where i < j {
            let d = abs(rooms[i].center.x - rooms[j].center.x) + abs(rooms[i].center.y - rooms[j].center.y)
            pairs.append((i, j, d))
        }
    }
    var parent = Array(rooms.indices)
    func find(_ p: Int) -> Int {
        var p = p
        while parent[p] != p { p = parent[p] }
        return p
    }
    var result: [(Int, Int)] = []
    for (i, j, _) in pairs.sorted(by: { ($0.2, $0.0, $0.1) < ($1.2, $1.0, $1.1) }) {
        let (a, b) = (find(i), find(j))
        if a != b {
            parent[a] = b
            result.append((i, j))
        }
    }
    return result
}

let rooms = [Room(x: 1, y: 1, width: 4, height: 3), Room(x: 10, y: 2, width: 3, height: 3),
             Room(x: 2, y: 9, width: 5, height: 2), Room(x: 12, y: 10, width: 3, height: 4)]
print(hallwayPairs(rooms).count, rooms[0].overlaps(rooms[1]))   // 3 false

Sorting by distance and then by the room indices makes the tie-breaking rule explicit. Swift’s sort is stable, so equal distances would keep the order in which the pairs were listed anyway; spelling out the rule means the result does not depend on how the list was built, which matters when it is built from a Set or Dictionary.

What would Swift print?

let a = (x: 0, y: 0, width: 4, height: 4)
let b = (x: 4, y: 2, width: 3, height: 3)
let c = (x: 6, y: 6, width: 2, height: 2)
func overlaps(_ p: (x: Int, y: Int, width: Int, height: Int), _ q: (x: Int, y: Int, width: Int, height: Int)) -> Bool {
    p.x <= q.x + q.width && q.x <= p.x + p.width && p.y <= q.y + q.height && q.y <= p.y + p.height
}
print(overlaps(a, b), overlaps(a, c), overlaps(b, c))

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answertrue false false

The test uses <=, so rooms that merely touch count as overlapping: a starts at x = 0 with width 4, b at x = 4, and they touch. That keeps a gap for walls between rooms. b covers rows 2 to 5 and c starts at row 6, so there is room between them, and a and c are even farther apart.

Guaranteeing a good world

A generator is hard to test by looking at its output, since every seed gives a different world. Test properties that every world must have (Lesson 23):

  • The same seed gives the same world, and different seeds usually different worlds.
  • Every floor tile is reachable from every other: a BFS from one floor tile (Lesson 43) visits them all.
  • Every floor tile is enclosed: no floor tile touches the edge of the map or an empty tile.
  • The world has at least some minimum number of rooms, and a reasonable fraction of floor.

Running these checks over a thousand seeds finds the rare seeds that break a generator, which no amount of looking at screenshots will.

Designing the modules

Before code, decide what each part knows. A design for Project 10:

Module Knows Does not know
World the grid of tiles, what a tile is how it was made, how it is drawn
WorldGenerator rooms, hallways, the seed the player, the screen, saving
Game the world, the avatar, the rules for moving keys, the screen, files
InputParser the input string format, like n123sddssaq how moves are applied
SaveFile the file format what the game state means
the SwiftUI app drawing, keys, the HUD the rules of the game

Each row can be written and tested alone. World is a plain value; the generator is a function from a seed to a World; the game is Lesson 52’s pure model. The app is thin. When the format of a save changes, only SaveFile changes; when rooms become caves, only WorldGenerator does.

Put the lines in order

Put the lines in order so the program prints true.

  1. let valid = values.allSatisfy { (0..<10).contains($0) }
  2. var first = SystemRandomNumberGenerator()
  3. print(valid)
  4. let values = (0..<3).map { _ in Int.random(in: 0..<10, using: &first) }

Show the correct program
var first = SystemRandomNumberGenerator()
let values = (0..<3).map { _ in Int.random(in: 0..<10, using: &first) }
let valid = values.allSatisfy { (0..<10).contains($0) }
print(valid)

Lab 52: Designing a world

These problems build a small generator that Project 10 can grow from. Each uses the SplitMix64 generator from the lesson.

Q0: What would Swift print?

What would Swift print?

struct Counter: RandomNumberGenerator {
    var n: UInt64 = 0
    mutating func next() -> UInt64 {
        n += 1
        return n
    }
}
var g = Counter()
_ = Int.random(in: 0..<100, using: &g)
_ = Bool.random(using: &g)
print(g.n >= 2)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answertrue

Every random function that takes using: asks the generator for at least one number. So consuming the generator in a different order, or skipping a call, changes every choice after it, which is why the order of random calls must be fixed.

Q1: Placing rooms

Write placeRooms(width:height:attempts:using:), which tries attempts random rooms, 3 to 8 tiles in each dimension, inside a map with a margin of one tile, and keeps those that do not overlap a kept room. Check that the same seed gives the same rooms.

Show solution
struct SplitMix64: RandomNumberGenerator {
    private var state: UInt64
    init(seed: UInt64) { state = seed }
    mutating func next() -> UInt64 {
        state &+= 0x9E3779B97F4A7C15
        var z = state
        z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9
        z = (z ^ (z >> 27)) &* 0x94D049BB133111EB
        return z ^ (z >> 31)
    }
}

struct Room: Equatable {
    let x: Int, y: Int, width: Int, height: Int
    func overlaps(_ o: Room) -> Bool {
        x <= o.x + o.width && o.x <= x + width && y <= o.y + o.height && o.y <= y + height
    }
}

func placeRooms(width: Int, height: Int, attempts: Int, using random: inout some RandomNumberGenerator) -> [Room] {
    var rooms: [Room] = []
    for _ in 0..<attempts {
        let w = Int.random(in: 3...8, using: &random)
        let h = Int.random(in: 3...8, using: &random)
        let x = Int.random(in: 1...(width - w - 2), using: &random)
        let y = Int.random(in: 1...(height - h - 2), using: &random)
        let room = Room(x: x, y: y, width: w, height: h)
        if !rooms.contains(where: room.overlaps) {
            rooms.append(room)
        }
    }
    return rooms
}

var g1 = SplitMix64(seed: 7), g2 = SplitMix64(seed: 7), g3 = SplitMix64(seed: 8)
let a = placeRooms(width: 60, height: 30, attempts: 40, using: &g1)
let b = placeRooms(width: 60, height: 30, attempts: 40, using: &g2)
let c = placeRooms(width: 60, height: 30, attempts: 40, using: &g3)
assert(a == b && a != c && a.count >= 4)
for (i, r) in a.enumerated() {
    assert(r.x >= 1 && r.y >= 1 && r.x + r.width <= 58 && r.y + r.height <= 28)
    for s in a[(i + 1)...] { assert(!r.overlaps(s)) }
}

The random calls happen in a fixed order in every attempt, whether or not the room is kept, so the sequence of rooms depends only on the seed.

Q2: Carving and connecting

Carve the rooms and L-shaped hallways into a grid of tiles (.floor, .wall, .nothing), connecting room centers along the pairs from the lesson’s hallwayPairs, then turn every nothing tile next to a floor into a wall. Check that all floor tiles are connected, with BFS, and that no floor touches nothing.

Show solution
enum Tile: Character { case nothing = " ", floor = ".", wall = "#" }

struct Room {
    let x: Int, y: Int, width: Int, height: Int
    var center: (x: Int, y: Int) { (x + width / 2, y + height / 2) }
}

func carve(_ rooms: [Room], pairs: [(Int, Int)], width: Int, height: Int) -> [[Tile]] {
    var tiles = Array(repeating: Array(repeating: Tile.nothing, count: width), count: height)
    for r in rooms {
        for y in r.y..<(r.y + r.height) { for x in r.x..<(r.x + r.width) { tiles[y][x] = .floor } }
    }
    for (i, j) in pairs {
        let (a, b) = (rooms[i].center, rooms[j].center)
        for x in min(a.x, b.x)...max(a.x, b.x) { tiles[a.y][x] = .floor }       // horizontal first
        for y in min(a.y, b.y)...max(a.y, b.y) { tiles[y][b.x] = .floor }       // then vertical
    }
    let floors = tiles
    for y in 0..<height {
        for x in 0..<width where floors[y][x] == .nothing {
            let nearFloor = (-1...1).contains { dy in (-1...1).contains { dx in
                let (ny, nx) = (y + dy, x + dx)
                return floors.indices.contains(ny) && floors[ny].indices.contains(nx) && floors[ny][nx] == .floor
            } }
            if nearFloor { tiles[y][x] = .wall }
        }
    }
    return tiles
}

let rooms = [Room(x: 1, y: 1, width: 4, height: 3), Room(x: 10, y: 2, width: 3, height: 3),
             Room(x: 2, y: 9, width: 5, height: 2)]
let world = carve(rooms, pairs: [(0, 1), (0, 2)], width: 16, height: 13)

var floorTiles: [(Int, Int)] = []
for y in world.indices { for x in world[y].indices where world[y][x] == .floor { floorTiles.append((y, x)) } }
var seen: Set<Int> = [floorTiles[0].0 * 100 + floorTiles[0].1]
var queue = [floorTiles[0]]
var head = 0
while head < queue.count {
    let (y, x) = queue[head]; head += 1
    for (dy, dx) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
        let (ny, nx) = (y + dy, x + dx)
        if world[ny][nx] == .floor, seen.insert(ny * 100 + nx).inserted { queue.append((ny, nx)) }
    }
}
assert(seen.count == floorTiles.count)
for (y, x) in floorTiles {
    for (dy, dx) in [(-1, 0), (1, 0), (0, -1), (0, 1)] { assert(world[y + dy][x + dx] != .nothing) }
}
print(world.map { String($0.map(\.rawValue)) }.joined(separator: "\n"))

Walls are computed from a copy of the floor layout, floors: deciding each tile from the grid while changing it would let new walls affect their neighbors’ decisions. Diagonal neighbors count, so corners are closed too. The BFS never indexes outside the grid because every floor is surrounded by walls, which is the property the last check confirms.

Q3: A thousand seeds

Combine Q1, the lesson’s hallwayPairs, and Q2 into generate(seed:), and check the connectivity and enclosure properties for seeds 0 to 999.

Show solution

Using the functions above, the test is a loop:

for seed in 0..<1_000 as Range<UInt64> {
    var random = SplitMix64(seed: seed)
    let rooms = placeRooms(width: 60, height: 30, attempts: 40, using: &random)
    let world = carve(rooms, pairs: hallwayPairs(rooms), width: 60, height: 30)
    assert(isConnected(world), "seed \(seed)")
    assert(isEnclosed(world), "seed \(seed)")
}

isConnected and isEnclosed are the two checks from Q2 made into functions. Including the seed in the failure message is what makes a failure reproducible: that one seed is the whole bug report. Project 10’s tests work the same way.

What’s next

With the world designed, the rest of Unit 7 turns to sorting, starting with the basic sorts.