typestar

word_freq.dart in Dart

A word-frequency table from split, map.update, and a two-key sort.

// Count word frequencies in a passage and chart the leaders.

const passage = 'the rain in maine falls mainly on the plain and '
    'the rain stays on the plain';

void main() {
  // Tally every word; update folds the increment into one call.
  final counts = <String, int>{};
  for (final word in passage.split(' ')) {
    counts.update(word, (n) => n + 1, ifAbsent: () => 1);
  }

  // Rank the entries, biggest first, ties broken by the word.
  final ranked = counts.entries.toList()
    ..sort((a, b) {
      final byCount = b.value.compareTo(a.value);
      return byCount != 0 ? byCount : a.key.compareTo(b.key);
    });

  print('${ranked.length} distinct words');
  print('word    ct bar');
  for (final entry in ranked) {
    final word = entry.key.padRight(7);
    final count = entry.value.toString().padLeft(2);
    print('$word $count ${'#' * entry.value}');
  }
}

How it works

  1. counts.update(word, ...) increments with ifAbsent for new words.
  2. The cascade ..sort ranks by count, ties alphabetical.
  3. '#' * entry.value draws each word's bar.

Keywords and builtins used here

The run, in numbers

Lines
27
Characters to type
819
Tokens
199
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 184 seconds.

Type this snippet

Step 1 of 3 in Encore, step 25 of 27 in Language basics.

← Previous Next →