DLLists, default implementations, and array lists
Trace a circular doubly linked list, decide what a protocol extension should provide, count resizing copies, and translate between two circular-array representations.
This discussion goes with Lessons 29, 30, and 31.
Q1: What would Swift print?
What would Swift print?
protocol Named {
var name: String { get }
}
extension Named {
func greeting() -> String { "Hi, " + name }
}
struct Robot: Named {
let name = "R2"
func greeting() -> String { "Beep" }
}
let r = Robot()
let n: any Named = r
print(r.greeting(), n.greeting())Show answer and explanation
AnswerBeep Hi, R2
greeting is not a requirement of Named, so a call through any Named uses
the extension’s version, chosen from the static type. Called on a Robot, the
compiler sees Robot’s own.
What would Swift print?
var capacity = 8
var copies = 0
for count in 0..<100 {
if count == capacity {
copies += count
capacity = capacity * 3 / 2
}
}
print(capacity, copies)Show answer and explanation
Answer135 255
Growing by half again resizes when the count reaches 8, 12, 18, 27, 40, 60, and 90, copying that many items each time: 255 in all. The capacity goes 8, 12, 18, 27, 40, 60, 90, 135; integer division rounds 27 × 3 / 2 = 40.5 down to 40. Any growth by a constant factor keeps total copying proportional to the number of items.
Q2: Trace a circular deque
Starting from an empty circular LinkedListDeque (Lesson 29), draw the ring
after each of these operations, and give sentinel.next.item and
sentinel.prev.item at the end.
deque.addLast(1)
deque.addFirst(0)
deque.addLast(2)
_ = deque.removeFirst()
deque.addFirst(9)
Show solution
addLast(1): S ⇄ 1 ⇄ (S)
addFirst(0): S ⇄ 0 ⇄ 1 ⇄ (S)
addLast(2): S ⇄ 0 ⇄ 1 ⇄ 2 ⇄ (S)
removeFirst(): S ⇄ 1 ⇄ 2 ⇄ (S)
addFirst(9): S ⇄ 9 ⇄ 1 ⇄ 2 ⇄ (S)(S) marks the ring closing back to the sentinel. At the end,
sentinel.next.item is 9 and sentinel.prev.item is 2. Every operation
changed exactly four links (two for the removal, since the removed node’s own
links do not matter), whatever the size of the list.
Q3: What belongs in the protocol?
A Deque protocol requires count, addFirst, addLast, removeFirst,
removeLast, and get(_:). For each of these extra members, decide whether
it should be a protocol requirement with a default implementation, an
extension-only method, or left to each type, and write the protocol and
extension.
isEmptyfirstandlasttoArray()removeAll()
Show solution
protocol Deque<Element> {
associatedtype Element
var count: Int { get }
mutating func addFirst(_ item: Element)
mutating func addLast(_ item: Element)
mutating func removeFirst() -> Element?
mutating func removeLast() -> Element?
func get(_ index: Int) -> Element?
func toArray() -> [Element] // requirement: types can do it faster
mutating func removeAll() // requirement: types can do it faster
}
extension Deque {
var isEmpty: Bool { count == 0 }
var first: Element? { self.get(0) } // `self.` : a bare `get` here would start a getter
var last: Element? { self.get(count - 1) }
func toArray() -> [Element] {
(0..<count).compactMap { get($0) }
}
mutating func removeAll() {
while removeFirst() != nil {}
}
}
struct ArrayBackedDeque<Element>: Deque {
private var items: [Element] = []
var count: Int { items.count }
mutating func addFirst(_ item: Element) { items.insert(item, at: 0) }
mutating func addLast(_ item: Element) { items.append(item) }
mutating func removeFirst() -> Element? { items.isEmpty ? nil : items.removeFirst() }
mutating func removeLast() -> Element? { items.popLast() }
func get(_ index: Int) -> Element? { items.indices.contains(index) ? items[index] : nil }
mutating func removeAll() { items.removeAll() }
}
var deque = ArrayBackedDeque<Int>()
deque.addLast(2)
deque.addFirst(1)
assert(deque.toArray() == [1, 2] && deque.first == 1 && deque.last == 2)
deque.removeAll()
assert(deque.isEmpty)isEmpty, first, and last have one obviously right implementation in terms
of the requirements, so they are extension-only. toArray() and removeAll()
have correct defaults that are slow for some types: the default toArray on a
linked list calls get repeatedly and takes quadratic time. Making them
requirements lets such types provide something better, and makes sure the
better version is used even through any Deque.
Q4: The cost of resizing
An AList starts with capacity 1. How many item copies does resizing cause
while adding n items, if each resize (a) adds 100 slots, (b) doubles the
capacity? Give exact numbers for n = 1,000 and describe how each grows with
n.
Show solution
func copies(for n: Int, grow: (Int) -> Int) -> Int {
var capacity = 1
var total = 0
for count in 0..<n where count == capacity {
total += count
capacity = grow(capacity)
}
return total
}
assert(copies(for: 1_000, grow: { $0 + 100 }) == 4_510)
assert(copies(for: 1_000, grow: { $0 * 2 }) == 1_023)Adding 100 slots resizes at 1, 101, 201, …, 901 items: 1 + 101 + 201 + … + 901
= 4,510 copies, and the total grows with the square of n, since there
are about n / 100 resizes, each copying up to n items. Doubling resizes at
1, 2, 4, …, 512 items: 1,023 copies, always less than 2n. That is the
difference between amortized constant time and linear time per add.
Q5: Exam-level: two ways to describe a ring
CS61B’s ArrayDeque records nextFirst and nextLast, the positions where
the next addFirst and addLast will write. Lesson 30 records first and
count instead. Write functions that convert each representation into the
other, given the capacity, and use them to find the physical index of item i
from nextFirst alone.
Show solution
func toFirstAndCount(nextFirst: Int, nextLast: Int, capacity: Int) -> (first: Int, count: Int) {
let first = (nextFirst + 1) % capacity
let count = (nextLast - first + capacity) % capacity
return (first, count)
}
func toNextFirstAndLast(first: Int, count: Int, capacity: Int) -> (nextFirst: Int, nextLast: Int) {
((first - 1 + capacity) % capacity, (first + count) % capacity)
}
func physicalIndex(of i: Int, nextFirst: Int, capacity: Int) -> Int {
(nextFirst + 1 + i) % capacity
}
// capacity 8: items a b c d stored at 6, 7, 0, 1
assert(toFirstAndCount(nextFirst: 5, nextLast: 2, capacity: 8) == (6, 4))
assert(toNextFirstAndLast(first: 6, count: 4, capacity: 8) == (5, 2))
assert(physicalIndex(of: 3, nextFirst: 5, capacity: 8) == 1)The % capacity in the count formula has a flaw worth noticing: a full
deque has nextLast == first, which gives a count of 0, exactly like an empty
one. With nextFirst and nextLast alone, full and empty look the same, so
CS61B’s version also stores size, and ours stores count. Resizing before the
deque becomes completely full is the other common fix.