typestar

temp_stats.swift en Swift

Una semana de temperaturas: min/max por clausura, barras y zip.

// 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()!))

Cómo funciona

  1. min y max con clausuras encuentran los días récord.
  2. El bucle desestructura cada tupla etiquetada y la grafica.
  3. zip(temps, temps.dropFirst()) empareja los cambios nocturnos.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
30
Caracteres a escribir
1066
Tokens
319
Ritmo de tres estrellas
65 tpm

Al ritmo de tres estrellas de 65 tokens por minuto, este intento toma unos 294 segundos.

Escribe este fragmento

Paso 3 de 3 en Bis; paso 27 de 27 en Fundamentos del lenguaje.

← Anterior