typestar

temp_stats.lua in Lua

A week of temperatures: index-tracked extremes, a bar chart, swings.

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

local days = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }
local temps = { -4.0, -1.5, 2.0, 3.5, 1.0, -2.5, -6.0 }

local coldest, warmest, sum = 1, 1, 0
for i, t in ipairs(temps) do
  sum = sum + t
  if t < temps[coldest] then coldest = i end
  if t > temps[warmest] then warmest = i end
end

print(string.format("Coldest: %s at %.1f C", days[coldest],
  temps[coldest]))
print(string.format("Warmest: %s at %.1f C", days[warmest],
  temps[warmest]))
print(string.format("Mean: %.1f C", sum / #temps))

-- Chart each day against the freezing line.
for i, t in ipairs(temps) do
  local len = math.max(1, math.floor(t + 7))
  local side = t > 0 and "above" or "below"
  print(string.format("%-4s %5.1f %s %s", days[i], t,
    string.rep("#", len), side))
end

local sharpest = 0
for i = 2, #temps do
  local swing = math.abs(temps[i] - temps[i - 1])
  if swing > sharpest then sharpest = swing end
end
print(string.format("Sharpest overnight swing: %.1f C", sharpest))

How it works

  1. One ipairs pass finds coldest, warmest, and the sum.
  2. The chart uses string.rep against the freezing line.
  3. A second pass compares neighbors for the sharpest swing.

Keywords and builtins used here

The run, in numbers

Lines
32
Characters to type
1019
Tokens
263
Three-star pace
60 tpm

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

Type this snippet

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

← Previous