temp_stats.st in Smalltalk
A week of temperatures: inject-picked extremes, bars, swings.
"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.
How it works
- Two injects find the coldest and warmest day indices.
- The chart pads columns and repeats $# against freezing.
- An interval collect: measures the overnight swings.
Keywords and builtins used here
StringTranscriptabsasFloataveragecrmaxprintStringsizetruncated
The run, in numbers
- Lines
- 37
- Characters to type
- 1270
- Tokens
- 295
- Three-star pace
- 55 tpm
At the three-star pace of 55 tokens a minute, this run takes about 322 seconds.
Step 3 of 3 in Encore, step 31 of 31 in Language basics.