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

Dictionaries, sets, and tuples

Look values up by key with dictionaries, test membership with sets, and group a few values with tuples, choosing the container that fits the question.

CS61A
Containers · Composing Programs 2.3
Documentation
Dictionary · Set

An array answers “what is at position 3?”. Many questions are not about positions: what is Ada’s phone number?, have we seen this word before?, what are the width and height? Swift has a container for each.

Dictionaries

A dictionary maps keys to values. [String: Int] maps strings to integers:

var ages = ["Ada": 36, "Grace": 85]
ages["Alan"] = 41          // add a new key
ages["Ada"] = 37           // replace a value
print(ages.count)          // 3
print(ages["Grace"]!)      // 85

Looking up a key that is not there is not an error. It gives nil, Swift’s “no value”, which is why the lookup above needs !. A lookup’s type is an optional, Int?, and printing it shows that:

What would Swift print?

let ages = ["Ada": 36]
print(ages["Ada"])
print(ages["Alan"])

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

Show answer and explanation

AnswerOptional(36)\nnil

ages["Ada"] is an Int? holding 36, which prints as Optional(36). There is no "Alan" key, so the second lookup is nil. Lesson 11 covers optionals properly; for now, read ? types as “maybe a value”.

Counting with a default

A lookup can supply a default for missing keys. That makes counting anything a two-line loop:

var counts: [String: Int] = [:]
for word in ["to", "be", "or", "not", "to", "be"] {
    counts[word, default: 0] += 1
}
print(counts["to"]!, counts["or"]!)   // 2 1

Order

A dictionary has no order. Iterating over one, or printing it, can list the pairs in any order, and the order can change between runs. When order matters, sort:

let stock = ["pears": 3, "apples": 5, "figs": 0]
for (fruit, count) in stock.sorted(by: { $0.key < $1.key }) {
    print(fruit, count)
}

Each element of a dictionary is a (key, value) pair, and the loop takes it apart into two names.

Transforming dictionaries

Dictionaries have their own higher-order functions. filter keeps some entries, mapValues changes every value and keeps the keys, and merge combines two dictionaries, with a closure that decides what happens when a key is in both:

let stock = ["apples": 5, "figs": 0, "pears": 3]
print(stock.filter { $0.value > 0 }.keys.sorted())   // ["apples", "pears"]
print(stock.mapValues { $0 * 2 }["apples"]!)         // 10
print(stock.values.reduce(0, +))                     // 8

var totals = ["a": 1, "b": 2]
totals.merge(["b": 20, "c": 3]) { old, new in old + new }
print(totals["b"]!, totals["c"]!)                    // 22 3

Sets

A set holds distinct values with no order. It answers one question quickly: is this value in here?

let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
print(vowels.contains("e"), vowels.contains("y"))   // true false

let seen = Set([3, 1, 3, 2, 1])
print(seen.count)   // 3, duplicates disappear
print(Set([1, 2]).union([2, 3]).sorted())   // [1, 2, 3]

What would Swift print?

let a: Set = [1, 2, 3]
let b: Set = [2, 3, 4]
print(a.intersection(b).sorted(), a.subtracting(b).count)

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

Show answer and explanation

Answer[2, 3] 1

The intersection holds the values in both sets, 2 and 3. Subtracting b from a leaves only 1, so its count is 1. Sorting first gives a predictable order to print.

contains on a set takes about the same time however large the set is. On an array it has to look at elements one by one. Lesson 18 measures the difference.

Set algebra

Sets support the operations from mathematics:

let a: Set = [1, 2, 3]
let b: Set = [2, 3, 4]
print(a.union(b).sorted())                 // [1, 2, 3, 4]
print(a.intersection(b).sorted())          // [2, 3]
print(a.subtracting(b).sorted())           // [1]
print(a.symmetricDifference(b).sorted())   // [1, 4], in one but not both
print(Set([2, 3]).isSubset(of: a))         // true

Tuples

A tuple groups a fixed number of values, possibly of different types. You met them in Lesson 2 as multiple return values:

let point = (x: 3, y: 4)
print(point.x, point.y)   // 3 4

let (a, b) = point        // take it apart
print(a + b)              // 7

A tuple is right for a small, fixed group that belongs together, like a coordinate or a result and its remainder. When the group grows, or needs behavior, Lesson 12’s structures are better.

What would Swift print?

func minMax(_ values: [Int]) -> (min: Int, max: Int) {
    (values.min()!, values.max()!)
}
let range = minMax([4, 9, 1, 7])
print(range.max - range.min)

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

Show answer and explanation

Answer8

The tuple holds 1 and 9, labeled min and max, and their difference is 8.

A tuple cannot be a dictionary key or a set element, because tuples are not Hashable. For a key made of two values, use an array like [row, column], as Lesson 18 does, or a structure.

Put the lines in order

Put the lines in order. The function counts each letter; the program prints 3.

  1. for letter in text {
  2. print(letterCounts("banana")["a"]!)
  3. }
  4. func letterCounts(_ text: String) -> [Character: Int] {
  5. }
  6. counts[letter, default: 0] += 1
  7. var counts: [Character: Int] = [:]
  8. return counts

Show the correct program
func letterCounts(_ text: String) -> [Character: Int] {
    var counts: [Character: Int] = [:]
    for letter in text {
        counts[letter, default: 0] += 1
    }
    return counts
}
print(letterCounts("banana")["a"]!)

Lab 9: Containers

Q0: What would Swift print?

What would Swift print?

var inventory = ["apples": 3]
inventory["apples", default: 0] += 2
inventory["pears", default: 0] += 1
print(inventory["apples"]!, inventory["pears"]!, inventory.count)

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

Show answer and explanation

Answer5 1 2

The default is used only when the key is missing: apples go from 3 to 5, and pears start at 0 and become 1. There are now two keys.

What would Swift print?

let seen: Set = ["b", "a", "b", "c", "a"]
print(seen.count, seen.sorted())

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

Show answer and explanation

Answer3 ["a", "b", "c"]

Duplicates collapse, leaving three distinct strings, which sorted() puts in order.

What would Swift print?

let point = (x: 3, y: -1)
let (a, b) = point
print(a * b, point.y)

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

Show answer and explanation

Answer-3 -1

Destructuring binds a to 3 and b to −1. The labeled element is still available as point.y.

Q1: Word counts

Write wordCounts(_:), which splits a string on spaces and returns how many times each word appears. text.split(separator: " ") gives the words.

func wordCounts(_ text: String) -> [String: Int] {
    // your code here
}
Show solution
func wordCounts(_ text: String) -> [String: Int] {
    var counts: [String: Int] = [:]
    for word in text.split(separator: " ") {
        counts[String(word), default: 0] += 1
    }
    return counts
}

let counts = wordCounts("the cat and the hat")
assert(counts["the"] == 2)
assert(counts["cat"] == 1)
assert(counts["dog"] == nil)
assert(counts.count == 4)

split returns Substrings, views into the original string like the ArraySlice from last lesson. String(word) makes each an independent string to use as a key.

Q2: First occurrences

Write uniqueInOrder(_:), which removes repeated values from an array but keeps each value where it first appeared.

func uniqueInOrder(_ values: [Int]) -> [Int] {
    // your code here
}
Show solution
func uniqueInOrder(_ values: [Int]) -> [Int] {
    var seen: Set<Int> = []
    var result: [Int] = []
    for value in values where !seen.contains(value) {
        seen.insert(value)
        result.append(value)
    }
    return result
}

assert(uniqueInOrder([3, 1, 3, 2, 1]) == [3, 1, 2])
assert(uniqueInOrder([]) == [])
assert(uniqueInOrder([5, 5, 5]) == [5])

Array(Set(values)) would remove duplicates too, but sets have no order, so it would lose the order the problem asks for. The set is only for fast membership; the array keeps the order.

Q3: Group by first letter

Write groupByFirstLetter(_:), which maps each first letter to the words that start with it, in their original order. Assume no word is empty.

func groupByFirstLetter(_ words: [String]) -> [Character: [String]] {
    // your code here
}
Show solution
func groupByFirstLetter(_ words: [String]) -> [Character: [String]] {
    var groups: [Character: [String]] = [:]
    for word in words {
        groups[word.first!, default: []].append(word)
    }
    return groups
}

let groups = groupByFirstLetter(["apple", "banana", "avocado", "blueberry", "cherry"])
assert(groups["a"] == ["apple", "avocado"])
assert(groups["b"] == ["banana", "blueberry"])
assert(groups["c"] == ["cherry"])
assert(groups.count == 3)

The default can be any value of the right type, here an empty array, and append modifies the value stored in the dictionary directly. The standard library also offers this as Dictionary(grouping: words) { $0.first! }.

Q4: Invert a dictionary

Write invert(_:), which maps each value to the sorted array of keys that had it.

func invert(_ dictionary: [String: Int]) -> [Int: [String]] {
    // your code here
}
Show solution
func invert(_ dictionary: [String: Int]) -> [Int: [String]] {
    var inverted: [Int: [String]] = [:]
    for (key, value) in dictionary {
        inverted[value, default: []].append(key)
    }
    return inverted.mapValues { $0.sorted() }
}

let inverted = invert(["a": 1, "b": 2, "c": 1])
assert(inverted[1] == ["a", "c"])
assert(inverted[2] == ["b"])
assert(invert([:]).isEmpty)

Sorting the keys at the end makes the result the same no matter which order the dictionary was visited in.

Q5: Letters in common

Write commonLetters(_:_:), the sorted array of characters that appear in both strings, each listed once.

func commonLetters(_ first: String, _ second: String) -> [Character] {
    // your code here
}
Show solution
func commonLetters(_ first: String, _ second: String) -> [Character] {
    Set(first).intersection(Set(second)).sorted()
}

assert(commonLetters("swift", "lift") == ["f", "i", "t"])
assert(commonLetters("abc", "xyz") == [])

A string is a sequence of characters, so Set(first) is its set of distinct letters.

Q6 (optional): Anagram groups

Write anagramGroups(_:), which groups words that are anagrams of each other. Return the groups with each group sorted, and the groups sorted by their first word.

func anagramGroups(_ words: [String]) -> [[String]] {
    // your code here
}
Show solution
func anagramGroups(_ words: [String]) -> [[String]] {
    var groups: [String: [String]] = [:]
    for word in words {
        let key = String(word.sorted())
        groups[key, default: []].append(word)
    }
    return groups.values.map { $0.sorted() }.sorted { $0[0] < $1[0] }
}

assert(anagramGroups(["listen", "silent", "enlist", "google", "gogole", "cat"])
       == [["cat"], ["enlist", "listen", "silent"], ["gogole", "google"]])

Two words are anagrams exactly when their sorted letters are equal, so the sorted letters make a good dictionary key.

What’s next

Next lesson: optionals, the type behind every ? and ! so far.