typestar

temp_stats.lua en Lua

Una semana de temperaturas: extremos por índice, barras y saltos.

-- 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))

Cómo funciona

  1. Una pasada de ipairs halla lo más frío, lo más cálido y la suma.
  2. El gráfico usa string.rep contra la línea de congelamiento.
  3. Una segunda pasada compara vecinos por el salto más brusco.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
32
Caracteres a escribir
1019
Tokens
263
Ritmo de tres estrellas
60 tpm

Al ritmo de tres estrellas de 60 tokens por minuto, este intento toma unos 263 segundos.

Escribe este fragmento

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

← Anterior