temp_stats.swift in Swift
A week of temperatures: min/max by closure, a bar chart, zip swings.
// Summarize a week of temperature readings: extremes, mean, swings.
import Foundation
let readings: [(day: String, temp: Double)] = [
("Mon", -4.0), ("Tue", -1.5), ("Wed", 2.0), ("Thu", 3.5),
("Fri", 1.0), ("Sat", -2.5), ("Sun", -6.0),
]
let temps = readings.map { $0.temp }
let coldest = readings.min { $0.temp < $1.temp }!
let warmest = readings.max { $0.temp < $1.temp }!
print("Coldest: \(coldest.day) at \(coldest.temp) C")
print("Warmest: \(warmest.day) at \(warmest.temp) C")
let mean = temps.reduce(0, +) / Double(temps.count)
print(String(format: "Mean: %.1f C", mean))
// Chart each day against the freezing line.
for (day, temp) in readings {
let length = max(1, Int(temp + 7))
let bar = String(repeating: "#", count: length)
let side = temp > 0 ? "above" : "below"
let label = String(format: "%5.1f", temp)
print("\(day) \(label) \(bar) \(side)")
}
// zip against the dropped-first self gives overnight pairs.
let swings = zip(temps, temps.dropFirst()).map { abs($1 - $0) }
print(String(format: "Sharpest overnight swing: %.1f C", swings.max()!))
How it works
minandmaxwith closures find the record days.- The loop destructures each labeled tuple and charts it.
zip(temps, temps.dropFirst())pairs the overnight changes.
Keywords and builtins used here
DoubleFoundationIntStringabscountdropFirstforimportinletmapmaxminprintreduce
The run, in numbers
- Lines
- 30
- Characters to type
- 1066
- Tokens
- 319
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 294 seconds.
Step 3 of 3 in Encore, step 27 of 27 in Language basics.