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

Hog

Build a two-player dice game in Swift, then use higher-order functions to write, test, and compare strategies that play it.

Hog is the first project in CS61A, and this is a Swift version of it. You will build a two-player dice game one function at a time, then write strategies, which are functions that decide how to play, and pass them to the game as values. By the end, your own strategy should beat a simple opponent most of the time.

The project uses everything in Unit 1 through Lesson 6: functions, conditionals and loops, higher-order functions, closures, and abstraction. It does not need recursion.

Getting started

Download the starter file, hog.swift, and put it in a folder of its own. It is one file with three parts: provided code at the top, the ten problems in the middle, and a test runner at the bottom.

Run the tests for everything, or for one problem:

swift hog.swift test
swift hog.swift test 3

At the start almost every check fails. After each problem, run its tests until they pass, then move on. When all ten are done, swift hog.swift test ends with All tests passed., and you can play against your own strategy:

swift hog.swift play

Write code only between the BEGIN PROBLEM and END PROBLEM lines, and do not change anything below // MARK: - Tests. The starter compiles as given, with a few warnings about unused variables in the unfinished play function; they disappear once you write it.

The rules

Two players take turns trying to be the first to reach 100 points. On each turn, the current player chooses to roll between zero and ten dice. The turn’s points are added to that player’s score.

  • Sow Sad. If any of the dice comes up 1, the turn scores exactly 1 point, no matter what the other dice show.
  • Boar Brawl. Rolling zero dice scores three times the absolute difference between the tens digit of the opponent’s score and the ones digit of the current player’s score, or 1 point if that is smaller. With a score of 21 against 46, that is 3 × |4 − 1| = 9.
  • Sus Fuss. After a turn, if a player’s score has exactly 3 or 4 positive factors, it increases to the next prime number. For example, 21 has the factors 1, 3, 7, and 21, so a score of 21 becomes 23.

The provided code

Read the top of the file before starting. Four definitions matter throughout:

  • typealias Dice = () -> Int: a die is a function that returns the next roll each time it is called. Real dice and test dice are both just functions with this type.
  • makeFairDice(sides:seed:) returns dice driven by a seeded pseudo-random generator, so the same seed replays the same game. makeTestDice(4, 6, 1) returns dice that roll 4, 6, 1, 4, 6, 1, … forever, which the tests use.
  • typealias Strategy = (Int, Int) -> Int takes your score and then the opponent’s, and returns how many dice to roll.
  • typealias Update = (Int, Int, Int, Dice) -> Int takes the number of dice, your score, the opponent’s score, and the dice, and returns your score after the turn. simpleUpdate is provided; you will write susUpdate.

Phase 1: Simulating a turn

Problem 1: rollDice

Implement rollDice(_:dice:). Call dice() exactly numRolls times, even after a 1 appears, because the dice function keeps its own state and the next turn must start from the right place. Return the sum of the outcomes, or 1 if any outcome was 1.

Problem 2: boarBrawl

Implement boarBrawl(player:opponent:) using / and % to take digits apart. A score of 100 has tens digit 0; a score below 10 has tens digit 0.

Problem 3: takeTurn

Implement takeTurn(_:player:opponent:dice:), which returns the points for one turn: Boar Brawl for zero dice, and rollDice otherwise. Rolling zero dice must not call dice at all.

Problem 4: Sus Fuss

Implement numFactors(_:), isPrime(_:), susPoints(_:), and susUpdate(_:_:_:_:). susUpdate is simpleUpdate followed by susPoints. Counting factors only needs to try divisors up to √n: every divisor k below √n comes with a partner n / k above it.

Phase 2: Playing a game

Problem 5: play

Implement play, which simulates a whole game and returns both final scores. Player 0 goes first, and players alternate turns. On each turn, ask the current player’s strategy how many dice to roll (passing the player’s own score first), then use update to compute that player’s new score. The game ends as soon as either score reaches goal; if a score already starts at the goal, no turns are played.

play never needs to know what the rules are. It takes them as a parameter, update, and the tests call it with both simpleUpdate and susUpdate. That is Lesson 6’s abstraction barrier at work.

Problem 6: alwaysRoll and isAlwaysRoll

alwaysRoll(_:) returns a strategy that ignores the scores. isAlwaysRoll checks whether a strategy gives the same answer for every pair of scores from 0 to 99: compare every answer with the answer for (0, 0).

Phase 3: Experiments

Problem 7: makeAveraged

makeAveraged(_:samples:) takes a function with no arguments and returns a function that calls it samples times and returns the average as a Double. Averaging a random function estimates its expected value.

Problem 8: maxScoringNumRolls

For each number of dice from 1 to 10, estimate the average score of a turn with makeAveraged, and return the number with the highest average. On a tie, keep the smaller number. With fair six-sided dice, the answer is 6: more dice score more, until the chance of rolling a 1 catches up.

Phase 4: Strategies

Problem 9: boarStrategy and susStrategy

boarStrategy rolls 0 when Boar Brawl would score at least threshold points, and numRolls dice otherwise. susStrategy is the same, but measures the whole gain from rolling 0, including any Sus Fuss bonus. The easiest way to compute that gain is to call susUpdate with zero dice; since it never rolls, any dice will do.

Problem 10: finalStrategy

Write your own strategy. The test plays 1,000 games against alwaysRoll(6), half as each player, with Sus Fuss, and checks that yours wins at least 55% of them. boarStrategy and susStrategy already win about two thirds, so start from one of them and improve it. Some ideas:

  • Roll zero when it would reach 100 and win outright.
  • Take less risk when you are far ahead, and more when you are far behind.
  • Avoid landing on a score that gives your opponent a large Boar Brawl.

Test ideas with winRate(_:games:), which is in the test section, by calling it temporarily from your code. Then play against your strategy with swift hog.swift play.