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

Review I

Exam-style review of Unit 4: dispatch puzzles, references and ARC, linked and array lists, protocols, and iterators, in the spirit of CS61B’s first midterm practice.

CS61B gives a timed practice exam before its first midterm. This homework is that practice for Unit 4. Try each problem on paper first, with a time limit of about ten minutes each, and only then run the code or open the solution.

Q1: What would Swift print?

What would Swift print?

class A {
    func f() -> String { "A.f " + g() }
    func g() -> String { "A.g" }
}
final class B: A {
    override func g() -> String { "B.g" }
}
func h(_ a: A) -> String { "h(A)" }
func h(_ b: B) -> String { "h(B)" }
let x: A = B()
print(x.f(), h(x), h(B()))

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

Show answer and explanation

AnswerA.f B.g h(A) h(B)

f is inherited, and inside it g() is dispatched dynamically to B’s version. The overloads of h are chosen by static type: x is declared A, so h(x) is h(A), while B() is statically a B.

What would Swift print?

var freed: [String] = []
final class Node {
    let name: String
    var next: Node?
    weak var back: Node?
    init(_ name: String) { self.name = name }
    deinit { freed.append(name) }
}
var a: Node? = Node("a")
var b: Node? = Node("b")
a!.next = b
b!.back = a
b = nil
print(freed.count)
a = nil
print(freed)

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

Show answer and explanation

Answer0 ["a", "b"]

After b = nil, node b is still held by a.next, so nothing is freed. When a goes, node a is freed first, which releases its next, and then b is freed. The weak back link never kept anything alive.

Q2: Remove every

Write removeEvery(_:) for an array list that stores its items in [Int?] slots with a count: it removes every occurrence of an item in a single pass, in linear time, keeping the order of the rest.

Show solution
struct AList {
    private(set) var items: [Int?]
    private(set) var count: Int

    init(_ values: [Int]) {
        items = values + [nil, nil]
        count = values.count
    }

    mutating func removeEvery(_ target: Int) {
        var write = 0
        for read in 0..<count where items[read] != target {
            items[write] = items[read]
            write += 1
        }
        for i in write..<count {
            items[i] = nil
        }
        count = write
    }

    var toArray: [Int] { (0..<count).map { items[$0]! } }
}

var list = AList([3, 1, 3, 3, 2, 3])
list.removeEvery(3)
assert(list.toArray == [1, 2] && list.count == 2 && list.items[2] == nil)

Removing each occurrence with a shifting remove(at:) would be quadratic. Two indices do it in one pass: read visits every item and write marks where the next kept item goes. Clearing the leftover slots avoids loitering.

Q3: Palindromes through an interface

Using only the Deque operations from Lesson 29 (count, addLast, removeFirst, removeLast), write a generic isPalindrome(_:) that works for any deque of Characters, and test it with a deque built on an array.

Show solution
protocol Deque<Element> {
    associatedtype Element
    var count: Int { get }
    mutating func addLast(_ item: Element)
    mutating func removeFirst() -> Element?
    mutating func removeLast() -> Element?
}

struct ArrayDeque<Element>: Deque {
    private var items: [Element] = []
    var count: Int { items.count }
    mutating func addLast(_ item: Element) { items.append(item) }
    mutating func removeFirst() -> Element? { items.isEmpty ? nil : items.removeFirst() }
    mutating func removeLast() -> Element? { items.popLast() }
}

func isPalindrome<D: Deque<Character>>(_ deque: D) -> Bool {
    var deque = deque
    while deque.count > 1 {
        if deque.removeFirst() != deque.removeLast() {
            return false
        }
    }
    return true
}

func deque(_ text: String) -> ArrayDeque<Character> {
    var result = ArrayDeque<Character>()
    for c in text {
        result.addLast(c)
    }
    return result
}

assert(isPalindrome(deque("racecar")) && isPalindrome(deque("abba")))
assert(!isPalindrome(deque("swift")) && isPalindrome(deque("")))

var deque = deque copies the parameter, so the check does not consume the caller’s deque when it is a value type. For a class-based deque it would, which is worth a line of documentation, or a copy-on-write wrapper from Lesson 33.

Q4: Find the bug

This circular deque’s get returns the wrong item for some inputs. Find a failing input, explain the bug, and fix it.

func get(_ i: Int) -> Element? {
    guard i < count else { return nil }
    return items[first + i]
}
Show solution

Whenever the items wrap around the end of the storage, first + i runs past the end: with capacity 8, first at 6, and 4 items, get(2) reads items[8], which crashes. It also accepts negative indices. The fix wraps the index and checks both bounds:

struct Ring<Element> {
    var items: [Element?]
    var first: Int
    var count: Int

    func get(_ i: Int) -> Element? {
        guard (0..<count).contains(i) else { return nil }
        return items[(first + i) % items.count]
    }
}

let ring = Ring(items: ["c", "d", nil, nil, nil, nil, "a", "b"], first: 6, count: 4)
assert((0..<4).map { ring.get($0)! } == ["a", "b", "c", "d"])
assert(ring.get(4) == nil && ring.get(-1) == nil)

A randomized comparison test (Lesson 27) finds this in a few operations; a hand-written test that never wraps around never does.

Q5: Equality and hashing

A Card has a rank and a suit. For a game in which suits do not matter, two cards are equal when their ranks are equal. Write == and hash(into:) for this rule, and show that a Set of cards then holds one card per rank.

Show solution
struct Card: Hashable {
    let rank: Int
    let suit: String

    static func == (lhs: Card, rhs: Card) -> Bool {
        lhs.rank == rhs.rank
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(rank)
    }
}

let hand: Set = [Card(rank: 5, suit: "hearts"), Card(rank: 5, suit: "spades"),
                 Card(rank: 9, suit: "clubs")]
assert(hand.count == 2)
assert(hand.contains(Card(rank: 9, suit: "diamonds")))

The hash uses exactly the property that == compares. Hashing the suit as well would give equal cards different hashes, and the set would usually keep both fives.

Q6 (optional): A grid iterator

Write a Sequence over a grid, given as [[Int?]], that yields the non-nil values in row-major order (row by row, left to right), skipping empty rows, without flattening the grid into a new array.

Show solution
struct GridValues: Sequence {
    let grid: [[Int?]]

    struct Iterator: IteratorProtocol {
        let grid: [[Int?]]
        var row = 0
        var column = 0

        mutating func next() -> Int? {
            while row < grid.count {
                if column < grid[row].count {
                    defer { column += 1 }
                    if let value = grid[row][column] {
                        return value
                    }
                } else {
                    row += 1
                    column = 0
                }
            }
            return nil
        }
    }

    func makeIterator() -> Iterator {
        Iterator(grid: grid)
    }
}

let grid: [[Int?]] = [[1, nil, 2], [], [nil], [3, 4]]
assert(Array(GridValues(grid: grid)) == [1, 2, 3, 4])
assert(Array(GridValues(grid: [])) == [])
assert(GridValues(grid: grid).reduce(0, +) == 10)

The iterator’s state is a position, row and column. defer advances the column whether or not the cell held a value, and reaching the end of a row moves to the next. The loop keeps going until it finds a value or runs out of rows, so empty rows and runs of nil cost nothing special.