typestar

word_freq.kt in Kotlin

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

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

val PASSAGE = "the rain in maine falls mainly on the plain and " +
    "the rain stays on the plain"

fun main() {
    // Tally every word into a mutable map, missing keys start at zero.
    val counts = mutableMapOf<String, Int>()
    for (word in PASSAGE.split(" ")) {
        counts[word] = (counts[word] ?: 0) + 1
    }

    // Rank the entries, biggest first, ties broken by the word itself.
    val ranked = counts.entries.sortedWith(
        compareByDescending<Map.Entry<String, Int>> { it.value }
            .thenBy { it.key })

    println("${ranked.size} distinct words")
    println("word    ct bar")
    for ((word, n) in ranked) {
        println("%-7s %2d %s".format(word, n, "#".repeat(n)))
    }
}

How it works

  1. split walks the passage; counts[word] = (counts[word] ?: 0) + 1 tallies.
  2. compareByDescending then thenBy ranks by count with ties alphabetical.
  3. "#".repeat(n) draws each word's bar in the final table.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
698
Tokens
143
Three-star pace
65 tpm

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

Type this snippet

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

← Previous Next →