typestar

temp_stats.jl in Julia

A week of temperatures: argmin/argmax, a bar chart, and diff.

# Summarize a week of temperature readings: extremes, mean, swings.

using Printf

readings = [
    ("Mon", -4.0), ("Tue", -1.5), ("Wed", 2.0), ("Thu", 3.5),
    ("Fri", 1.0), ("Sat", -2.5), ("Sun", -6.0),
]

temps = last.(readings)
coldest = argmin(temps)
warmest = argmax(temps)

println("Coldest: $(readings[coldest][1]) at $(temps[coldest]) C")
println("Warmest: $(readings[warmest][1]) at $(temps[warmest]) C")
@printf("Mean: %.1f C\n", sum(temps) / length(temps))

# Chart each day against the freezing line.
for (day, t) in readings
    bar = "#"^max(1, Int(floor(t + 7)))
    side = t > 0 ? "above" : "below"
    @printf("%-4s %5.1f %s %s\n", day, t, bar, side)
end

# diff gives neighbor-to-neighbor changes in one call.
swings = abs.(diff(temps))
@printf("Sharpest overnight swing: %.1f C\n", maximum(swings))

How it works

  1. argmin and argmax find the record days by index.
  2. The loop charts each day against freezing with "#"^n.
  3. abs.(diff(temps)) gives overnight swings in one expression.

Keywords and builtins used here

The run, in numbers

Lines
27
Characters to type
799
Tokens
241
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 222 seconds.

Type this snippet

Step 3 of 3 in Encore, step 27 of 27 in Language basics.

← Previous