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

Swift warm-up

Short problems that exercise the Swift the data structures half relies on: optionals, loops, dictionaries, two-dimensional arrays, value types with custom equality, and a little recursion.

This homework goes with Lesson 25, like CS61B’s first coding homework. Each problem is small; the goal is fluency. Put everything in hw11.swift with the assert lines, and run it with swift hw11.swift.

Q1: The smallest item

Write smallest(_:), which returns the smallest integer in an array, or nil if the array is empty, with a loop and without calling min().

Show solution
func smallest(_ values: [Int]) -> Int? {
    guard var best = values.first else {
        return nil
    }
    for value in values.dropFirst() where value < best {
        best = value
    }
    return best
}

assert(smallest([4, -2, 7]) == -2)
assert(smallest([5]) == 5)
assert(smallest([]) == nil)

Q2: Hailstones

Starting from a positive integer n, the hailstone sequence halves n when it is even and replaces it with 3n + 1 when it is odd, until it reaches 1. Write hailstone(_:), which returns the whole sequence as an array.

Show solution
func hailstone(_ n: Int) -> [Int] {
    precondition(n > 0)
    var sequence = [n]
    var current = n
    while current != 1 {
        current = current % 2 == 0 ? current / 2 : 3 * current + 1
        sequence.append(current)
    }
    return sequence
}

assert(hailstone(6) == [6, 3, 10, 5, 16, 8, 4, 2, 1])
assert(hailstone(1) == [1])
assert(hailstone(27).count == 112)

Nobody has proven that the loop always ends; that is the Collatz conjecture. It has been checked for every starting value anyone has tried.

Q3: The most common words

Write topWords(_:k:), which returns the k most frequent words in a text (split on spaces, ignoring case), most frequent first, with ties in alphabetical order.

Show solution
func topWords(_ text: String, k: Int) -> [String] {
    var counts: [String: Int] = [:]
    for word in text.lowercased().split(separator: " ") {
        counts[String(word), default: 0] += 1
    }
    let ordered = counts.sorted { a, b in
        a.value != b.value ? a.value > b.value : a.key < b.key
    }
    return ordered.prefix(k).map(\.key)
}

let text = "the cat and the hat and the bat"
assert(topWords(text, k: 2) == ["the", "and"])
assert(topWords(text, k: 4) == ["the", "and", "bat", "cat"])
assert(topWords("", k: 3).isEmpty)

Sorting a dictionary gives an array of key–value pairs. The comparator compares counts first and falls back to the words, so equal counts come out in a predictable order: important for tests, since a dictionary itself has no order.

Q4: Rotating a matrix

Write rotated(_:), which returns a matrix, given as an array of rows, rotated 90 degrees clockwise. The matrix need not be square.

Show solution
func rotated(_ matrix: [[Int]]) -> [[Int]] {
    guard let columns = matrix.first?.count else {
        return []
    }
    return (0..<columns).map { column in
        matrix.reversed().map { row in row[column] }
    }
}

assert(rotated([[1, 2], [3, 4]]) == [[3, 1], [4, 2]])
assert(rotated([[1, 2, 3]]) == [[1], [2], [3]])
assert(rotated([[1], [2], [3]]) == [[3, 2, 1]])
assert(rotated(rotated(rotated(rotated([[1, 2], [3, 4], [5, 6]])))) == [[1, 2], [3, 4], [5, 6]])

Row c of the result is column c of the original, read from the bottom up. Rotating four times gives back the original, a useful property to test.

Q5: Pascal’s triangle

Write pascalRow(_:), returning row n of Pascal’s triangle (row 0 is [1]), by building each row from the one before.

Show solution
func pascalRow(_ n: Int) -> [Int] {
    var row = [1]
    for _ in 0..<n {
        row = zip([0] + row, row + [0]).map(+)
    }
    return row
}

assert(pascalRow(0) == [1])
assert(pascalRow(4) == [1, 4, 6, 4, 1])
assert(pascalRow(10).reduce(0, +) == 1024)

Each entry is the sum of the two above it. Padding the previous row with a 0 on either side and adding the two versions position by position does every entry at once, including the 1s at the ends.

Q6: Fractions

Write a structure Fraction that is always stored in lowest terms with a positive denominator, so that the synthesized == is correct: 2/4 and -1/-2 must both equal 1/2. Add + and a description like "1/2".

Show solution
func gcd(_ a: Int, _ b: Int) -> Int {
    b == 0 ? abs(a) : gcd(b, a % b)
}

struct Fraction: Equatable, CustomStringConvertible {
    let numerator: Int
    let denominator: Int

    init(_ numerator: Int, _ denominator: Int) {
        precondition(denominator != 0, "zero denominator")
        let sign = denominator < 0 ? -1 : 1
        let divisor = gcd(numerator, denominator)
        self.numerator = sign * numerator / divisor
        self.denominator = sign * denominator / divisor
    }

    static func + (a: Fraction, b: Fraction) -> Fraction {
        Fraction(a.numerator * b.denominator + b.numerator * a.denominator, a.denominator * b.denominator)
    }

    var description: String { "\(numerator)/\(denominator)" }
}

assert(Fraction(2, 4) == Fraction(1, 2) && Fraction(-1, -2) == Fraction(1, 2))
assert(Fraction(1, 3) + Fraction(1, 6) == Fraction(1, 2))
assert(Fraction(3, -9).description == "-1/3")
assert(Fraction(0, 5) == Fraction(0, 1))

Choosing a canonical form in the initializer means every fraction with the same value has the same stored properties. Then the automatically generated == and, if needed, Hashable are automatically right, which is simpler and safer than writing a custom == that cross-multiplies.

Q7 (optional): The longest run

Write longestRun(_:), which returns the value that repeats the most times in a row, and how many times. For ties, return the earliest run.

Show solution
func longestRun(_ values: [Int]) -> (value: Int, length: Int)? {
    guard let first = values.first else {
        return nil
    }
    var best = (value: first, length: 1)
    var current = best
    for value in values.dropFirst() {
        current = value == current.value ? (value, current.length + 1) : (value, 1)
        if current.length > best.length {
            best = current
        }
    }
    return best
}

assert(longestRun([1, 2, 2, 3, 3, 3, 2])! == (3, 3))
assert(longestRun([5, 5, 7, 7])! == (5, 2))     // the earlier run wins a tie
assert(longestRun([4])! == (4, 1))
assert(longestRun([]) == nil)

Using > rather than >= is what makes the earliest run win ties: a later run only replaces the best one if it is strictly longer.