temp_stats.dart in Dart
A week of temperatures: extremes, mean, a bar chart, and swings.
// Summarize a week of temperature readings: extremes, mean, swings.
const readings = [
('Mon', -4.0),
('Tue', -1.5),
('Wed', 2.0),
('Thu', 3.5),
('Fri', 1.0),
('Sat', -2.5),
('Sun', -6.0),
];
void main() {
final temps = readings.map((r) => r.$2).toList();
final coldest = readings.reduce((a, b) => a.$2 <= b.$2 ? a : b);
final warmest = readings.reduce((a, b) => a.$2 >= b.$2 ? a : b);
print('Coldest: ${coldest.$1} at ${coldest.$2} C');
print('Warmest: ${warmest.$1} at ${warmest.$2} C');
final mean = temps.reduce((a, b) => a + b) / temps.length;
print('Mean: ${mean.toStringAsFixed(1)} C');
// Chart each day against the freezing line.
for (final (day, t) in readings) {
final bar = '#' * (t + 7).toInt().clamp(1, 20);
final side = t > 0 ? 'above' : 'below';
final label = t.toStringAsFixed(1).padLeft(5);
print('${day.padRight(4)} $label $bar $side');
}
var sharpest = 0.0;
for (var i = 1; i < temps.length; i++) {
final swing = (temps[i] - temps[i - 1]).abs();
if (swing > sharpest) sharpest = swing;
}
print('Sharpest overnight swing: ${sharpest.toStringAsFixed(1)} C');
}
How it works
reducefinds the coldest and warmest records by comparison.- The loop destructures each
(day, t)record and charts it. clampkeeps the bars printable; the swing loop tracks neighbors.
Keywords and builtins used here
constfinalforifinvarvoid
The run, in numbers
- Lines
- 37
- Characters to type
- 1084
- Tokens
- 386
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 356 seconds.
Step 3 of 3 in Encore, step 27 of 27 in Language basics.