typestar

temp_stats.st en Smalltalk

Una semana de temperaturas: extremos por inject, barras, saltos.

"Summarize a week of temperature readings: extremes, mean, swings."
| days temps coldest warmest swings |
days := #('Mon' 'Tue' 'Wed' 'Thu' 'Fri' 'Sat' 'Sun').
temps := #(-4.0 -1.5 2.0 3.5 1.0 -2.5 -6.0).

coldest := (1 to: temps size)
    inject: 1 into: [:best :i |
        (temps at: i) < (temps at: best) ifTrue: [i] ifFalse: [best]].
warmest := (1 to: temps size)
    inject: 1 into: [:best :i |
        (temps at: i) > (temps at: best) ifTrue: [i] ifFalse: [best]].

Transcript show: 'Coldest: ', (days at: coldest), ' at ',
    (temps at: coldest) printString, ' C'; cr.
Transcript show: 'Warmest: ', (days at: warmest), ' at ',
    (temps at: warmest) printString, ' C'; cr.
Transcript show: 'Mean: ',
    (temps average asFloat printShowingDecimalPlaces: 1), ' C'; cr.

"Chart each day against the freezing line."
1 to: temps size do: [:i |
    | t len |
    t := temps at: i.
    len := 1 max: (t + 7) truncated.
    Transcript
        show: ((days at: i) padRightTo: 4);
        show: ((t printShowingDecimalPlaces: 1)
            padLeftTo: 6);
        show: ' ';
        show: (String new: len withAll: $#);
        show: (t > 0 ifTrue: [' above'] ifFalse: [' below']);
        cr].

swings := (2 to: temps size) collect: [:i |
    ((temps at: i) - (temps at: i - 1)) abs].
Transcript show: 'Sharpest overnight swing: ',
    (swings max printShowingDecimalPlaces: 1), ' C'; cr.

Cómo funciona

  1. Dos inject hallan los índices del día más frío y más cálido.
  2. El gráfico rellena columnas y repite $# contra el congelamiento.
  3. Un collect: sobre un intervalo mide los saltos nocturnos.

El intento, en números

Líneas
37
Caracteres a escribir
1270
Tokens
295
Ritmo de tres estrellas
55 tpm

Al ritmo de tres estrellas de 55 tokens por minuto, este intento toma unos 322 segundos.

Escribe este fragmento

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

← Anterior