temp_stats.kt in Kotlin
A week of temperatures: extremes, mean, a bar chart, and overnight swings.
// Summarize a week of temperature readings: extremes, mean, swings.
import kotlin.math.abs
val READINGS = listOf(
"Mon" to -4.0, "Tue" to -1.5, "Wed" to 2.0, "Thu" to 3.5,
"Fri" to 1.0, "Sat" to -2.5, "Sun" to -6.0,
)
fun main() {
val temps = READINGS.map { it.second }
val coldest = READINGS.minByOrNull { it.second }!!
val warmest = READINGS.maxByOrNull { it.second }!!
println("Coldest: ${coldest.first} at ${coldest.second} C")
println("Warmest: ${warmest.first} at ${warmest.second} C")
println("Mean: %.1f C".format(temps.average()))
// Chart each day against the freezing line.
for ((day, t) in READINGS) {
val bar = "#".repeat((t + 7).toInt().coerceAtLeast(1))
val side = if (t > 0) "above" else "below"
println("%-4s %5.1f %s %s".format(day, t, bar, side))
}
val swings = temps.zipWithNext { a, b -> b - a }
println("Sharpest overnight swing: %.1f C".format(
swings.maxOf { abs(it) }))
}
How it works
minByOrNullandmaxByOrNullfind the cold and warm records.- The loop destructures each day and charts it against freezing.
zipWithNextpairs neighbors;maxOfwithabsfinds the sharpest swing.
Keywords and builtins used here
elseforfunifimportinitmainval
The run, in numbers
- Lines
- 29
- Characters to type
- 903
- Tokens
- 252
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 233 seconds.
Step 3 of 3 in Encore, step 27 of 27 in Language basics.