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

DLLists, default implementations, and array lists

Trace a circular doubly linked list, decide what a protocol extension should provide, count resizing copies, and translate between two circular-array representations.

This discussion goes with Lessons 29, 30, and 31.

Q1: What would Swift print?

What would Swift print?

protocol Named {
    var name: String { get }
}
extension Named {
    func greeting() -> String { "Hi, " + name }
}
struct Robot: Named {
    let name = "R2"
    func greeting() -> String { "Beep" }
}
let r = Robot()
let n: any Named = r
print(r.greeting(), n.greeting())

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

Show answer and explanation

AnswerBeep Hi, R2

greeting is not a requirement of Named, so a call through any Named uses the extension’s version, chosen from the static type. Called on a Robot, the compiler sees Robot’s own.

What would Swift print?

var capacity = 8
var copies = 0
for count in 0..<100 {
    if count == capacity {
        copies += count
        capacity = capacity * 3 / 2
    }
}
print(capacity, copies)

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

Show answer and explanation

Answer135 255

Growing by half again resizes when the count reaches 8, 12, 18, 27, 40, 60, and 90, copying that many items each time: 255 in all. The capacity goes 8, 12, 18, 27, 40, 60, 90, 135; integer division rounds 27 × 3 / 2 = 40.5 down to 40. Any growth by a constant factor keeps total copying proportional to the number of items.

Q2: Trace a circular deque

Starting from an empty circular LinkedListDeque (Lesson 29), draw the ring after each of these operations, and give sentinel.next.item and sentinel.prev.item at the end.

deque.addLast(1)
deque.addFirst(0)
deque.addLast(2)
_ = deque.removeFirst()
deque.addFirst(9)
Show solution
addLast(1):    S ⇄ 1 ⇄ (S)
addFirst(0):   S ⇄ 0 ⇄ 1 ⇄ (S)
addLast(2):    S ⇄ 0 ⇄ 1 ⇄ 2 ⇄ (S)
removeFirst(): S ⇄ 1 ⇄ 2 ⇄ (S)
addFirst(9):   S ⇄ 9 ⇄ 1 ⇄ 2 ⇄ (S)

(S) marks the ring closing back to the sentinel. At the end, sentinel.next.item is 9 and sentinel.prev.item is 2. Every operation changed exactly four links (two for the removal, since the removed node’s own links do not matter), whatever the size of the list.

Q3: What belongs in the protocol?

A Deque protocol requires count, addFirst, addLast, removeFirst, removeLast, and get(_:). For each of these extra members, decide whether it should be a protocol requirement with a default implementation, an extension-only method, or left to each type, and write the protocol and extension.

  • isEmpty
  • first and last
  • toArray()
  • removeAll()
Show solution
protocol Deque<Element> {
    associatedtype Element
    var count: Int { get }
    mutating func addFirst(_ item: Element)
    mutating func addLast(_ item: Element)
    mutating func removeFirst() -> Element?
    mutating func removeLast() -> Element?
    func get(_ index: Int) -> Element?

    func toArray() -> [Element]      // requirement: types can do it faster
    mutating func removeAll()        // requirement: types can do it faster
}

extension Deque {
    var isEmpty: Bool { count == 0 }
    var first: Element? { self.get(0) }         // `self.` : a bare `get` here would start a getter
    var last: Element? { self.get(count - 1) }

    func toArray() -> [Element] {
        (0..<count).compactMap { get($0) }
    }

    mutating func removeAll() {
        while removeFirst() != nil {}
    }
}

struct ArrayBackedDeque<Element>: Deque {
    private var items: [Element] = []
    var count: Int { items.count }
    mutating func addFirst(_ item: Element) { items.insert(item, at: 0) }
    mutating func addLast(_ item: Element) { items.append(item) }
    mutating func removeFirst() -> Element? { items.isEmpty ? nil : items.removeFirst() }
    mutating func removeLast() -> Element? { items.popLast() }
    func get(_ index: Int) -> Element? { items.indices.contains(index) ? items[index] : nil }
    mutating func removeAll() { items.removeAll() }
}

var deque = ArrayBackedDeque<Int>()
deque.addLast(2)
deque.addFirst(1)
assert(deque.toArray() == [1, 2] && deque.first == 1 && deque.last == 2)
deque.removeAll()
assert(deque.isEmpty)

isEmpty, first, and last have one obviously right implementation in terms of the requirements, so they are extension-only. toArray() and removeAll() have correct defaults that are slow for some types: the default toArray on a linked list calls get repeatedly and takes quadratic time. Making them requirements lets such types provide something better, and makes sure the better version is used even through any Deque.

Q4: The cost of resizing

An AList starts with capacity 1. How many item copies does resizing cause while adding n items, if each resize (a) adds 100 slots, (b) doubles the capacity? Give exact numbers for n = 1,000 and describe how each grows with n.

Show solution
func copies(for n: Int, grow: (Int) -> Int) -> Int {
    var capacity = 1
    var total = 0
    for count in 0..<n where count == capacity {
        total += count
        capacity = grow(capacity)
    }
    return total
}

assert(copies(for: 1_000, grow: { $0 + 100 }) == 4_510)
assert(copies(for: 1_000, grow: { $0 * 2 }) == 1_023)

Adding 100 slots resizes at 1, 101, 201, …, 901 items: 1 + 101 + 201 + … + 901 = 4,510 copies, and the total grows with the square of n, since there are about n / 100 resizes, each copying up to n items. Doubling resizes at 1, 2, 4, …, 512 items: 1,023 copies, always less than 2n. That is the difference between amortized constant time and linear time per add.

Q5: Exam-level: two ways to describe a ring

CS61B’s ArrayDeque records nextFirst and nextLast, the positions where the next addFirst and addLast will write. Lesson 30 records first and count instead. Write functions that convert each representation into the other, given the capacity, and use them to find the physical index of item i from nextFirst alone.

Show solution
func toFirstAndCount(nextFirst: Int, nextLast: Int, capacity: Int) -> (first: Int, count: Int) {
    let first = (nextFirst + 1) % capacity
    let count = (nextLast - first + capacity) % capacity
    return (first, count)
}

func toNextFirstAndLast(first: Int, count: Int, capacity: Int) -> (nextFirst: Int, nextLast: Int) {
    ((first - 1 + capacity) % capacity, (first + count) % capacity)
}

func physicalIndex(of i: Int, nextFirst: Int, capacity: Int) -> Int {
    (nextFirst + 1 + i) % capacity
}

// capacity 8: items a b c d stored at 6, 7, 0, 1
assert(toFirstAndCount(nextFirst: 5, nextLast: 2, capacity: 8) == (6, 4))
assert(toNextFirstAndLast(first: 6, count: 4, capacity: 8) == (5, 2))
assert(physicalIndex(of: 3, nextFirst: 5, capacity: 8) == 1)

The % capacity in the count formula has a flaw worth noticing: a full deque has nextLast == first, which gives a count of 0, exactly like an empty one. With nextFirst and nextLast alone, full and empty look the same, so CS61B’s version also stores size, and ours stores count. Resizing before the deque becomes completely full is the other common fix.