Swift warm-up
Short problems that exercise the Swift the data structures half relies on: optionals, loops, dictionaries, two-dimensional arrays, value types with custom equality, and a little recursion.
This homework goes with Lesson 25, like CS61B’s first coding homework. Each
problem is small; the goal is fluency. Put everything in hw11.swift with the
assert lines, and run it with swift hw11.swift.
Q1: The smallest item
Write smallest(_:), which returns the smallest integer in an array, or nil
if the array is empty, with a loop and without calling min().
Show solution
func smallest(_ values: [Int]) -> Int? {
guard var best = values.first else {
return nil
}
for value in values.dropFirst() where value < best {
best = value
}
return best
}
assert(smallest([4, -2, 7]) == -2)
assert(smallest([5]) == 5)
assert(smallest([]) == nil)Q2: Hailstones
Starting from a positive integer n, the hailstone sequence halves n when it
is even and replaces it with 3n + 1 when it is odd, until it reaches 1. Write
hailstone(_:), which returns the whole sequence as an array.
Show solution
func hailstone(_ n: Int) -> [Int] {
precondition(n > 0)
var sequence = [n]
var current = n
while current != 1 {
current = current % 2 == 0 ? current / 2 : 3 * current + 1
sequence.append(current)
}
return sequence
}
assert(hailstone(6) == [6, 3, 10, 5, 16, 8, 4, 2, 1])
assert(hailstone(1) == [1])
assert(hailstone(27).count == 112)Nobody has proven that the loop always ends; that is the Collatz conjecture. It has been checked for every starting value anyone has tried.
Q3: The most common words
Write topWords(_:k:), which returns the k most frequent words in a text
(split on spaces, ignoring case), most frequent first, with ties in
alphabetical order.
Show solution
func topWords(_ text: String, k: Int) -> [String] {
var counts: [String: Int] = [:]
for word in text.lowercased().split(separator: " ") {
counts[String(word), default: 0] += 1
}
let ordered = counts.sorted { a, b in
a.value != b.value ? a.value > b.value : a.key < b.key
}
return ordered.prefix(k).map(\.key)
}
let text = "the cat and the hat and the bat"
assert(topWords(text, k: 2) == ["the", "and"])
assert(topWords(text, k: 4) == ["the", "and", "bat", "cat"])
assert(topWords("", k: 3).isEmpty)Sorting a dictionary gives an array of key–value pairs. The comparator compares counts first and falls back to the words, so equal counts come out in a predictable order: important for tests, since a dictionary itself has no order.
Q4: Rotating a matrix
Write rotated(_:), which returns a matrix, given as an array of rows,
rotated 90 degrees clockwise. The matrix need not be square.
Show solution
func rotated(_ matrix: [[Int]]) -> [[Int]] {
guard let columns = matrix.first?.count else {
return []
}
return (0..<columns).map { column in
matrix.reversed().map { row in row[column] }
}
}
assert(rotated([[1, 2], [3, 4]]) == [[3, 1], [4, 2]])
assert(rotated([[1, 2, 3]]) == [[1], [2], [3]])
assert(rotated([[1], [2], [3]]) == [[3, 2, 1]])
assert(rotated(rotated(rotated(rotated([[1, 2], [3, 4], [5, 6]])))) == [[1, 2], [3, 4], [5, 6]])Row c of the result is column c of the original, read from the bottom up.
Rotating four times gives back the original, a useful property to test.
Q5: Pascal’s triangle
Write pascalRow(_:), returning row n of Pascal’s triangle (row 0 is [1]),
by building each row from the one before.
Show solution
func pascalRow(_ n: Int) -> [Int] {
var row = [1]
for _ in 0..<n {
row = zip([0] + row, row + [0]).map(+)
}
return row
}
assert(pascalRow(0) == [1])
assert(pascalRow(4) == [1, 4, 6, 4, 1])
assert(pascalRow(10).reduce(0, +) == 1024)Each entry is the sum of the two above it. Padding the previous row with a 0 on either side and adding the two versions position by position does every entry at once, including the 1s at the ends.
Q6: Fractions
Write a structure Fraction that is always stored in lowest terms with a
positive denominator, so that the synthesized == is correct: 2/4 and
-1/-2 must both equal 1/2. Add + and a description like "1/2".
Show solution
func gcd(_ a: Int, _ b: Int) -> Int {
b == 0 ? abs(a) : gcd(b, a % b)
}
struct Fraction: Equatable, CustomStringConvertible {
let numerator: Int
let denominator: Int
init(_ numerator: Int, _ denominator: Int) {
precondition(denominator != 0, "zero denominator")
let sign = denominator < 0 ? -1 : 1
let divisor = gcd(numerator, denominator)
self.numerator = sign * numerator / divisor
self.denominator = sign * denominator / divisor
}
static func + (a: Fraction, b: Fraction) -> Fraction {
Fraction(a.numerator * b.denominator + b.numerator * a.denominator, a.denominator * b.denominator)
}
var description: String { "\(numerator)/\(denominator)" }
}
assert(Fraction(2, 4) == Fraction(1, 2) && Fraction(-1, -2) == Fraction(1, 2))
assert(Fraction(1, 3) + Fraction(1, 6) == Fraction(1, 2))
assert(Fraction(3, -9).description == "-1/3")
assert(Fraction(0, 5) == Fraction(0, 1))Choosing a canonical form in the initializer means every fraction with the
same value has the same stored properties. Then the automatically generated
== and, if needed, Hashable are automatically right, which is simpler and
safer than writing a custom == that cross-multiplies.
Q7 (optional): The longest run
Write longestRun(_:), which returns the value that repeats the most times in
a row, and how many times. For ties, return the earliest run.
Show solution
func longestRun(_ values: [Int]) -> (value: Int, length: Int)? {
guard let first = values.first else {
return nil
}
var best = (value: first, length: 1)
var current = best
for value in values.dropFirst() {
current = value == current.value ? (value, current.length + 1) : (value, 1)
if current.length > best.length {
best = current
}
}
return best
}
assert(longestRun([1, 2, 2, 3, 3, 3, 2])! == (3, 3))
assert(longestRun([5, 5, 7, 7])! == (5, 2)) // the earlier run wins a tie
assert(longestRun([4])! == (4, 1))
assert(longestRun([]) == nil)Using > rather than >= is what makes the earliest run win ties: a later run
only replaces the best one if it is strictly longer.