Review I
Exam-style review of Unit 4: dispatch puzzles, references and ARC, linked and array lists, protocols, and iterators, in the spirit of CS61B’s first midterm practice.
CS61B gives a timed practice exam before its first midterm. This homework is that practice for Unit 4. Try each problem on paper first, with a time limit of about ten minutes each, and only then run the code or open the solution.
Q1: What would Swift print?
What would Swift print?
class A {
func f() -> String { "A.f " + g() }
func g() -> String { "A.g" }
}
final class B: A {
override func g() -> String { "B.g" }
}
func h(_ a: A) -> String { "h(A)" }
func h(_ b: B) -> String { "h(B)" }
let x: A = B()
print(x.f(), h(x), h(B()))Show answer and explanation
AnswerA.f B.g h(A) h(B)
f is inherited, and inside it g() is dispatched dynamically to B’s
version. The overloads of h are chosen by static type: x is declared A,
so h(x) is h(A), while B() is statically a B.
What would Swift print?
var freed: [String] = []
final class Node {
let name: String
var next: Node?
weak var back: Node?
init(_ name: String) { self.name = name }
deinit { freed.append(name) }
}
var a: Node? = Node("a")
var b: Node? = Node("b")
a!.next = b
b!.back = a
b = nil
print(freed.count)
a = nil
print(freed)Show answer and explanation
Answer0
["a", "b"]
After b = nil, node b is still held by a.next, so nothing is freed. When
a goes, node a is freed first, which releases its next, and then b is
freed. The weak back link never kept anything alive.
Q2: Remove every
Write removeEvery(_:) for an array list that stores its items in
[Int?] slots with a count: it removes every occurrence of an item in a
single pass, in linear time, keeping the order of the rest.
Show solution
struct AList {
private(set) var items: [Int?]
private(set) var count: Int
init(_ values: [Int]) {
items = values + [nil, nil]
count = values.count
}
mutating func removeEvery(_ target: Int) {
var write = 0
for read in 0..<count where items[read] != target {
items[write] = items[read]
write += 1
}
for i in write..<count {
items[i] = nil
}
count = write
}
var toArray: [Int] { (0..<count).map { items[$0]! } }
}
var list = AList([3, 1, 3, 3, 2, 3])
list.removeEvery(3)
assert(list.toArray == [1, 2] && list.count == 2 && list.items[2] == nil)Removing each occurrence with a shifting remove(at:) would be quadratic. Two
indices do it in one pass: read visits every item and write marks where the
next kept item goes. Clearing the leftover slots avoids loitering.
Q3: Palindromes through an interface
Using only the Deque operations from Lesson 29 (count, addLast,
removeFirst, removeLast), write a generic isPalindrome(_:) that works for
any deque of Characters, and test it with a deque built on an array.
Show solution
protocol Deque<Element> {
associatedtype Element
var count: Int { get }
mutating func addLast(_ item: Element)
mutating func removeFirst() -> Element?
mutating func removeLast() -> Element?
}
struct ArrayDeque<Element>: Deque {
private var items: [Element] = []
var count: Int { items.count }
mutating func addLast(_ item: Element) { items.append(item) }
mutating func removeFirst() -> Element? { items.isEmpty ? nil : items.removeFirst() }
mutating func removeLast() -> Element? { items.popLast() }
}
func isPalindrome<D: Deque<Character>>(_ deque: D) -> Bool {
var deque = deque
while deque.count > 1 {
if deque.removeFirst() != deque.removeLast() {
return false
}
}
return true
}
func deque(_ text: String) -> ArrayDeque<Character> {
var result = ArrayDeque<Character>()
for c in text {
result.addLast(c)
}
return result
}
assert(isPalindrome(deque("racecar")) && isPalindrome(deque("abba")))
assert(!isPalindrome(deque("swift")) && isPalindrome(deque("")))var deque = deque copies the parameter, so the check does not consume the
caller’s deque when it is a value type. For a class-based deque it would, which
is worth a line of documentation, or a copy-on-write wrapper from Lesson 33.
Q4: Find the bug
This circular deque’s get returns the wrong item for some inputs. Find a
failing input, explain the bug, and fix it.
func get(_ i: Int) -> Element? {
guard i < count else { return nil }
return items[first + i]
}
Show solution
Whenever the items wrap around the end of the storage, first + i runs past
the end: with capacity 8, first at 6, and 4 items, get(2) reads
items[8], which crashes. It also accepts negative indices. The fix wraps the
index and checks both bounds:
struct Ring<Element> {
var items: [Element?]
var first: Int
var count: Int
func get(_ i: Int) -> Element? {
guard (0..<count).contains(i) else { return nil }
return items[(first + i) % items.count]
}
}
let ring = Ring(items: ["c", "d", nil, nil, nil, nil, "a", "b"], first: 6, count: 4)
assert((0..<4).map { ring.get($0)! } == ["a", "b", "c", "d"])
assert(ring.get(4) == nil && ring.get(-1) == nil)A randomized comparison test (Lesson 27) finds this in a few operations; a hand-written test that never wraps around never does.
Q5: Equality and hashing
A Card has a rank and a suit. For a game in which suits do not matter,
two cards are equal when their ranks are equal. Write == and hash(into:)
for this rule, and show that a Set of cards then holds one card per rank.
Show solution
struct Card: Hashable {
let rank: Int
let suit: String
static func == (lhs: Card, rhs: Card) -> Bool {
lhs.rank == rhs.rank
}
func hash(into hasher: inout Hasher) {
hasher.combine(rank)
}
}
let hand: Set = [Card(rank: 5, suit: "hearts"), Card(rank: 5, suit: "spades"),
Card(rank: 9, suit: "clubs")]
assert(hand.count == 2)
assert(hand.contains(Card(rank: 9, suit: "diamonds")))The hash uses exactly the property that == compares. Hashing the suit as well
would give equal cards different hashes, and the set would usually keep both
fives.
Q6 (optional): A grid iterator
Write a Sequence over a grid, given as [[Int?]], that yields the non-nil
values in row-major order (row by row, left to right), skipping empty rows,
without flattening the grid into a new array.
Show solution
struct GridValues: Sequence {
let grid: [[Int?]]
struct Iterator: IteratorProtocol {
let grid: [[Int?]]
var row = 0
var column = 0
mutating func next() -> Int? {
while row < grid.count {
if column < grid[row].count {
defer { column += 1 }
if let value = grid[row][column] {
return value
}
} else {
row += 1
column = 0
}
}
return nil
}
}
func makeIterator() -> Iterator {
Iterator(grid: grid)
}
}
let grid: [[Int?]] = [[1, nil, 2], [], [nil], [3, 4]]
assert(Array(GridValues(grid: grid)) == [1, 2, 3, 4])
assert(Array(GridValues(grid: [])) == [])
assert(GridValues(grid: grid).reduce(0, +) == 10)The iterator’s state is a position, row and column. defer advances the
column whether or not the cell held a value, and reaching the end of a row
moves to the next. The loop keeps going until it finds a value or runs out of
rows, so empty rows and runs of nil cost nothing special.