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

Compression and complexity

Making data smaller: prefix-free codes, Huffman coding with a priority queue, LZW’s growing dictionary, why no algorithm compresses everything, and a first look at P, NP, and the problems nobody knows how to solve quickly.

CS61B
Compression · Textbook Ch. 37, Ch. 38
Documentation
Data

A text file stores every character in 8 bits, whether it is a common e or a rare q. Compression exploits that waste. CS61B’s last technical lectures use it to bring together several data structures of this unit, heaps, trees, tries, and hash maps, and then step back to ask about problems that no known algorithm solves efficiently. This lesson does both.

Prefix-free codes

Lossless compression makes data smaller in a way that can be undone exactly. The simplest idea is to give frequent symbols short codes and rare ones long codes, as Morse code does. But variable-length codes must be decodable: if a is 0 and b is 01, then 01 could be b, or a followed by something.

A code is prefix-free if no symbol’s code is the beginning of another’s. Then a sequence of bits can be decoded left to right without ambiguity: read bits until they match a code, output its symbol, and continue. Prefix-free codes are exactly the codes that can be drawn as a binary trie (Lesson 50) with symbols only at the leaves: 0 goes left, 1 goes right, and a leaf is a complete code.

Huffman coding

Given how often each symbol occurs, which prefix-free code gives the shortest encoding? David Huffman found the answer in 1952, as a student, and it is short: put every symbol in a priority queue (Lesson 41) as a one-node tree, weighted by its frequency; then repeatedly remove the two lightest trees, join them under a new parent whose weight is their sum, and put it back. When one tree remains, it is the code.

indirect enum HuffmanTree {
    case leaf(Character, weight: Int)
    case node(HuffmanTree, HuffmanTree, weight: Int)

    var weight: Int {
        switch self {
        case .leaf(_, let w), .node(_, _, let w): w
        }
    }

    func codes(prefix: String = "") -> [Character: String] {
        switch self {
        case .leaf(let c, _):
            [c: prefix.isEmpty ? "0" : prefix]
        case .node(let left, let right, _):
            left.codes(prefix: prefix + "0").merging(right.codes(prefix: prefix + "1")) { a, _ in a }
        }
    }
}

func huffman(_ text: String) -> HuffmanTree {
    var counts: [Character: Int] = [:]
    for c in text { counts[c, default: 0] += 1 }
    // A sorted array as the priority queue, to keep the example short; ties by character.
    var queue = counts.map { HuffmanTree.leaf($0.key, weight: $0.value) }
    func key(_ t: HuffmanTree) -> (Int, String) {
        if case .leaf(let c, let w) = t { return (w, String(c)) } else { return (t.weight, "~") }
    }
    while queue.count > 1 {
        queue.sort { key($0) < key($1) }
        let (a, b) = (queue.removeFirst(), queue.removeFirst())
        queue.append(.node(a, b, weight: a.weight + b.weight))
    }
    return queue[0]
}

let text = "abracadabra"
let codes = huffman(text).codes()
let encoded = text.map { codes[$0]! }.joined()
print(codes.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }, encoded.count, text.count * 8)
// ["a=0", "b=110", "c=100", "d=101", "r=111"] 23 88

a, which occurs five times, gets a one-bit code; the rarer letters get three bits. The whole word takes 23 bits instead of 88. Huffman’s algorithm is optimal: no prefix-free code gives a shorter encoding for these frequencies. With a heap, building the tree for R symbols takes O(R log R).

To decode, the receiver needs the tree too, so a compressed file stores it at the start. Decoding walks the tree bit by bit and restarts at the root after each leaf.

What would Swift print?

let codes: [String: Character] = ["0": "a", "10": "b", "110": "c", "111": "d"]
var output = ""
var current = ""
for bit in "0101100111" {
    current.append(bit)
    if let c = codes[current] {
        output.append(c)
        current = ""
    }
}
print(output)

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

Show answer and explanation

Answerabcad

Reading left to right: 0 is a; 1 is not a code, 10 is b; 110 is c; 0 is a; 111 is d. Because the code is prefix-free, the first match is always the right one.

LZW: learning as you go

Huffman coding treats each symbol alone. Real data has repeated phrases: words in text, runs of pixels. LZW (Lempel, Ziv, and Welch) builds a dictionary of phrases as it reads, starting with single characters. At each step it outputs the code for the longest phrase in the dictionary that matches the input, then adds that phrase plus the next character as a new entry:

func lzwEncode(_ text: String) -> [Int] {
    var dictionary: [String: Int] = [:]
    for c in Set(text).sorted() { dictionary[String(c)] = dictionary.count }
    var phrase = ""
    var output: [Int] = []
    for c in text {
        let extended = phrase + String(c)
        if dictionary[extended] != nil {
            phrase = extended
        } else {
            output.append(dictionary[phrase]!)
            dictionary[extended] = dictionary.count
            phrase = String(c)
        }
    }
    if !phrase.isEmpty { output.append(dictionary[phrase]!) }
    return output
}

let codesOut = lzwEncode("abababababab")
print(codesOut, codesOut.count)   // [0, 1, 2, 4, 3, 6] 6

Twelve characters become six codes, and the longer the repetition, the longer the phrases the dictionary learns. The decoder rebuilds the same dictionary from the codes it receives, so the dictionary never has to be sent. LZW-style algorithms are behind GIF images and, in refined forms, ZIP and PNG.

You cannot compress everything

Could an algorithm compress every file, even by one bit? No, by counting. There are 2ⁿ files of exactly n bits, but only 2ⁿ − 1 files shorter than n bits (2⁰ + 2¹ + … + 2ⁿ⁻¹). A lossless compressor must map different inputs to different outputs, so it cannot map all 2ⁿ inputs into fewer possible outputs. Every compressor makes some files larger. Compression works on real data because real data is far from random, and random data, such as already-compressed files, does not compress.

CS61B takes this further. The best possible compression of a file is the shortest program that prints it: its Kolmogorov complexity. A million digits of π are very compressible by this measure, a short program computes them, though they look random. But no program can compute the Kolmogorov complexity of every file: the question is uncomputable, not just hard.

Hard problems: P and NP

Some problems are not uncomputable, just, as far as anyone knows, slow. Lesson 43’s Hamilton path problem, “is there a path visiting every vertex exactly once?”, has no known algorithm much faster than trying the possibilities, which grow exponentially. Yet a proposed path is easy to check.

  • P is the class of yes-or-no problems that can be solved in polynomial time, O(Nᵏ) for some k: connectivity, shortest paths, sorting-based questions.
  • NP is the class of yes-or-no problems whose yes-answers can be checked in polynomial time, given a certificate such as the path itself: Hamilton path, scheduling with deadlines, Sudoku of any size, and every problem in P.

A problem is NP-complete if it is in NP and every NP problem reduces to it (Lesson 47): Hamilton path, 3-coloring a graph, and boolean satisfiability are examples. Thousands of NP-complete problems are known, and a polynomial algorithm for any one of them would give one for all of NP. Whether P = NP is the most famous open question in computer science. Most researchers believe P ≠ NP, which would mean these problems have no efficient algorithm at all. Much of modern cryptography rests on problems like them being hard.

Put the lines in order

Put the lines in order so the program prints 7.

  1. shorter += 1 << length
  2. let n = 3
  3. var shorter = 0
  4. }
  5. for length in 0..<n {
  6. print(shorter)

Show the correct program
let n = 3
var shorter = 0
for length in 0..<n {
    shorter += 1 << length
}
print(shorter)

Lab 57: Compression

Q0: What would Swift print?

What would Swift print?

let frequencies = ["a": 45, "b": 13, "c": 12, "d": 16, "e": 9, "f": 5]
let codeLengths = ["a": 1, "b": 3, "c": 3, "d": 3, "e": 4, "f": 4]
let bits = frequencies.map { $0.value * codeLengths[$0.key]! }.reduce(0, +)
let fixed = frequencies.values.reduce(0, +) * 3
print(bits, fixed)

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

Show answer and explanation

Answer224 300

With a fixed 3-bit code, 100 symbols take 300 bits. The Huffman code lengths for these frequencies, from the classic textbook example, give 45 + 3 × (13 + 12 + 16) + 4 × (9 + 5) = 224 bits, 25% less.

Q1: Decoding with the tree

Write decode(_:with:), which decodes a string of bits by walking the lesson’s HuffmanTree, and check that decoding the encoding of several texts gives them back.

Show solution
indirect enum HuffmanTree {
    case leaf(Character, weight: Int)
    case node(HuffmanTree, HuffmanTree, weight: Int)
    var weight: Int {
        switch self { case .leaf(_, let w), .node(_, _, let w): w }
    }
    func codes(prefix: String = "") -> [Character: String] {
        switch self {
        case .leaf(let c, _): [c: prefix.isEmpty ? "0" : prefix]
        case .node(let l, let r, _): l.codes(prefix: prefix + "0").merging(r.codes(prefix: prefix + "1")) { a, _ in a }
        }
    }
}

func huffman(_ text: String) -> HuffmanTree {
    var counts: [Character: Int] = [:]
    for c in text { counts[c, default: 0] += 1 }
    var queue = counts.sorted { $0.key < $1.key }.map { HuffmanTree.leaf($0.key, weight: $0.value) }
    while queue.count > 1 {
        queue.sort { $0.weight < $1.weight }
        let (a, b) = (queue.removeFirst(), queue.removeFirst())
        queue.append(.node(a, b, weight: a.weight + b.weight))
    }
    return queue[0]
}

func decode(_ bits: String, with tree: HuffmanTree) -> String {
    if case .leaf(let c, _) = tree {                      // a one-symbol text
        return String(repeating: c, count: bits.count)
    }
    var output = ""
    var node = tree
    for bit in bits {
        guard case .node(let left, let right, _) = node else { break }
        node = bit == "0" ? left : right
        if case .leaf(let c, _) = node {
            output.append(c)
            node = tree
        }
    }
    return output
}

for text in ["abracadabra", "mississippi river", "aaaa", "the quick brown fox"] {
    let tree = huffman(text)
    let codes = tree.codes()
    let bits = text.map { codes[$0]! }.joined()
    assert(decode(bits, with: tree) == text)
    assert(bits.count <= text.count * 8)
}

A text with one distinct symbol has a tree that is a single leaf; giving it the code 0 and decoding one symbol per bit handles that edge case. Sorting with a stable sort (Lesson 54) after an initial sort by character makes the tree the same on every run.

Q2: LZW decoding

Write lzwDecode(_:alphabet:), the inverse of the lesson’s encoder, given the same starting alphabet. The tricky case: a code can refer to the entry the encoder added at the previous step, which the decoder has not added yet. That entry is always the previous phrase plus its own first character.

Show solution
func lzwEncode(_ text: String, alphabet: [Character]) -> [Int] {
    var dictionary: [String: Int] = [:]
    for c in alphabet { dictionary[String(c)] = dictionary.count }
    var phrase = ""
    var output: [Int] = []
    for c in text {
        let extended = phrase + String(c)
        if dictionary[extended] != nil {
            phrase = extended
        } else {
            output.append(dictionary[phrase]!)
            dictionary[extended] = dictionary.count
            phrase = String(c)
        }
    }
    if !phrase.isEmpty { output.append(dictionary[phrase]!) }
    return output
}

func lzwDecode(_ codes: [Int], alphabet: [Character]) -> String {
    var entries = alphabet.map { String($0) }
    guard let first = codes.first else { return "" }
    var previous = entries[first]
    var output = previous
    for code in codes.dropFirst() {
        let current = code < entries.count ? entries[code] : previous + String(previous.first!)
        output += current
        entries.append(previous + String(current.first!))
        previous = current
    }
    return output
}

let alphabet: [Character] = ["a", "b", "r", "c", "d"]
for text in ["abababababab", "abracadabra", "aaaaaaa", ""] {
    assert(lzwDecode(lzwEncode(text, alphabet: alphabet), alphabet: alphabet) == text)
}

"aaaaaaa" exercises the tricky case: the encoder adds “aa” and immediately outputs its code, before the decoder has seen enough to know it. The rule “previous phrase plus its own first character” recovers it.

Q3 (optional): Compressing random data

Show the counting argument in action: “compress” 10,000 random 16-character strings of the letters a and b with the Huffman code of each string, counting the bits for the code table as a byte per symbol plus a byte per code length, and compare with the 16 bits that a plain one-bit-per-letter encoding needs.

Show solution
var generator = SystemRandomNumberGenerator()
var larger = 0
for _ in 0..<10_000 {
    let text = String((0..<16).map { _ in Bool.random(using: &generator) ? Character("a") : "b" })
    // Huffman gives each of at most two symbols a 1-bit code: 16 bits of data,
    // plus a table of 2 bytes (16 bits) per distinct symbol.
    let dataBits = 16
    let tableBits = Set(text).count * 16
    if dataBits + tableBits > 16 { larger += 1 }
}
assert(larger == 10_000)

Random strings of two letters are already as compact as one bit per letter; Huffman cannot improve on that, and the table it must store makes every result larger. Real compressors store a flag saying “stored uncompressed” for such inputs, which costs a few bits and caps the damage, but, as the counting argument proves, cannot avoid it entirely.

What’s next

The last lesson steps back from algorithms to the people who use software, and to where to go from here.