Async and Practical
Histogram Counts as Bars
Tallying a small sample into a Map<String, int> and rendering each count as a string of # characters builds a tiny histogram. The bar width is just '#' * count, which makes the proportions visible at a glance.
Program
Play the program to count six samples and render them as compact bars.
histogram.dart
Replay: real traced execution (multi-file project)
void main() {
var samples = ['red', 'blue', 'red', 'green', 'red', 'blue'];
var counts = <String, int>{};
for (var s in samples) {
counts[s] = (counts[s] ?? 0) + 1;
}
var bars = counts.entries
.map((e) => '${e.key}: ${'#' * e.value}')
.toList();
print(bars.join(' | '));
}
samples ← [red, blue, red, green, red, blue]
1void main() {2 var samples = ['red', 'blue', 'red', 'green', 'red', 'blue'];3 var counts = <String, int>{};values this step[red, blue, red, green, red, blue]samplescounts ← {}
2var samples = ['red', 'blue', 'red', 'green', 'red', 'blue'];3var counts = <String, int>{};4for (var s in samples) {values this step{}countsloop ← tally 6 samples
3var counts = <String, int>{};4for (var s in samples) {5 counts[s] = (counts[s] ?? 0) + 1;values this steptally 6 samplesloopcounts ← {red: 3, blue: 2, green: 1}
4for (var s in samples) {5 counts[s] = (counts[s] ?? 0) + 1;6}values this step{red: 3, blue: 2, green: 1}countsbars ← red ### | blue ## | green #
8 .map((e) => '${e.key}: ${'#' * e.value}')9 .toList();10print(bars.join(' | '));values this stepred ### | blue ## | green #barsprint(bars.join(' | '));
9 .toList();10 print(bars.join(' | '));11}outputred: ### | blue: ## | green: #values this stepred ### | blue ## | green #bars
counter map
`counts[s] = (counts[s] ?? 0) + 1` defaults missing keys to zero before adding one.
string repetition
`'#' * count` repeats `#` once per occurrence, turning a tally into a tiny bar.
insertion order
Default Dart maps keep insertion order, so the bars render in first-seen order.