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

Control and environment diagrams

Draw environment diagrams for function calls, trace conditionals and loops, and write loop-based functions on the digits of a number.

This discussion goes with Lessons 2 and 3. Environment diagrams come first: they are the tool CS61A uses for every question about what a name means. The rules are in Lesson 5; for now, one frame per function call is enough.

Q1: Draw the frames

Draw the environment diagram for this program at the moment it prints, and say what it prints.

func square(_ x: Int) -> Int {
    x * x
}
func sumOfSquares(_ a: Int, _ b: Int) -> Int {
    let x = square(a)
    return x + square(b)
}
let x = 2
print(sumOfSquares(x, x + 1))
Show solution

It prints 13.

Global frame
  square       │ func square(_:)  [parent = Global]
  sumOfSquares │ func sumOfSquares(_:_:)  [parent = Global]
  x            │ 2

f1: sumOfSquares  [parent = Global]
  a      │ 2
  b      │ 3
  x      │ 4
  Return │ 13

f2: square  [parent = Global]
  x      │ 2
  Return │ 4

f3: square  [parent = Global]
  x      │ 3
  Return │ 9

There are three different names x, in three frames: the global x (2), the local x in f1 (4), and each call’s parameter x. None of them affects the others. The argument x + 1 is evaluated in the global frame, before f1 exists.

Q2: What would Swift print?

What would Swift print?

func check(_ n: Int) -> String {
    if n > 10 {
        return "big"
    } else if n > 5 {
        return "medium"
    }
    return "small"
}
print(check(10), check(11), check(5))

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

Show answer and explanation

Answermedium big small

10 is not greater than 10, but it is greater than 5. 11 is big. 5 is not greater than 5, so it falls through to the final return.

What would Swift print?

var n = 12
var steps = 0
while n > 1 {
    n = n / 2
    steps += 1
}
print(n, steps)

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

Show answer and explanation

Answer1 3

12 becomes 6, then 3, then 1 (integer division), which ends the loop after 3 steps.

What would Swift print?

var total = 0
for i in 1...4 {
    total = total * 10 + i
}
print(total)

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

Show answer and explanation

Answer1234

Each pass shifts the total one decimal place left and appends i: 1, 12, 123, 1234.

Q3: Is it prime?

Write isPrime(_:) with a while loop. A number is prime if it is greater than 1 and has no divisor other than 1 and itself. You only need to test divisors k with k × k ≤ n.

func isPrime(_ n: Int) -> Bool {
    // your code here
}
Show solution
func isPrime(_ n: Int) -> Bool {
    if n < 2 {
        return false
    }
    var k = 2
    while k * k <= n {
        if n % k == 0 {
            return false
        }
        k += 1
    }
    return true
}

assert(!isPrime(10))
assert(isPrime(7))
assert(!isPrime(1))
assert(isPrime(97))

If n had a divisor larger than √n, it would pair with one smaller than √n, which the loop would already have found.

Q4: Unique digits

Write uniqueDigits(_:), the number of different digits in a non-negative integer. uniqueDigits(8675309) is 7 and uniqueDigits(1313131) is 2. Hint: first write hasDigit(_:_:), which checks whether a number contains a given digit, and then count the digits 0 through 9 it contains.

func hasDigit(_ n: Int, _ digit: Int) -> Bool {
    // your code here
}

func uniqueDigits(_ n: Int) -> Int {
    // your code here
}
Show solution
func hasDigit(_ n: Int, _ digit: Int) -> Bool {
    var rest = n
    repeat {
        if rest % 10 == digit {
            return true
        }
        rest /= 10
    } while rest > 0
    return false
}

func uniqueDigits(_ n: Int) -> Int {
    var count = 0
    for digit in 0...9 where hasDigit(n, digit) {
        count += 1
    }
    return count
}

assert(uniqueDigits(8675309) == 7)
assert(uniqueDigits(1313131) == 2)
assert(uniqueDigits(13173131) == 3)
assert(uniqueDigits(10000) == 2)
assert(uniqueDigits(101) == 2)
assert(uniqueDigits(0) == 1)

Splitting the problem in two keeps each function simple: hasDigit walks the digits of one number, and uniqueDigits asks ten yes-or-no questions. repeat-while makes sure the single digit of 0 is checked.

Q5: Find the bug

This function should return how many times the digit 7 appears in n, but countSevens(707) returns 1. Find the mistake without running it, and fix it.

func countSevens(_ n: Int) -> Int {
    var rest = n
    var count = 0
    while rest > 10 {
        if rest % 10 == 7 {
            count += 1
        }
        rest /= 10
    }
    return count
}
print(countSevens(707))
Show solution

The loop stops when rest is 10 or less, so the leading digit is never checked once it is alone: for 707, the last pass leaves rest at 7, and 7 > 10 is false. The condition should be rest > 0.

func countSevens(_ n: Int) -> Int {
    var rest = n
    var count = 0
    while rest > 0 {
        if rest % 10 == 7 {
            count += 1
        }
        rest /= 10
    }
    return count
}
assert(countSevens(707) == 2)
assert(countSevens(10) == 0)
assert(countSevens(7) == 1)

Boundary conditions are where loops go wrong. Checking the smallest inputs, a one-digit number here, finds this kind of bug fastest.