How to group words in a string by the first N letters in Kotlin

2 Answers

0 votes
fun groupByFirstNLetters(s: String, n: Int = 3): Map<String, List<String>> {
    val regex = Regex("[A-Za-z]+")
    val words = regex.findAll(s.lowercase()).map { it.value }

    val groups = mutableMapOf<String, MutableList<String>>()

    for (w in words) {
        if (w.length >= n) {
            val prefix = w.substring(0, n)
            groups.getOrPut(prefix) { mutableListOf() }.add(w)
        }
    }

    return groups
}

fun main() {
    val s = "The lowly inhabitants of the lowland were surprised to see " +
            "the lower branches of the trees."

    val groups = groupByFirstNLetters(s, 3)

    // Print version 1
    for ((prefix, words) in groups) {
        println("$prefix : $words")
    }

    println()

    // Print version 2
    for ((prefix, words) in groups) {
        println("$prefix: ${words.joinToString(", ")}")
    }
}




/*
run:

the : [the, the, the, the]
low : [lowly, lowland, lower]
inh : [inhabitants]
wer : [were]
sur : [surprised]
see : [see]
bra : [branches]
tre : [trees]

the: the, the, the, the
low: lowly, lowland, lower
inh: inhabitants
wer: were
sur: surprised
see: see
bra: branches
tre: trees

*/

 



answered Mar 13 by avibootz
0 votes
fun groupByFirstNLetters(s: String, n: Int = 3): Map<String, List<String>> =
    Regex("[A-Za-z]+")
        .findAll(s.lowercase())
        .map { it.value }
        .filter { it.length >= n }
        .groupBy { it.substring(0, n) }


fun main() {
    val s = "The lowly inhabitants of the lowland were surprised to see " +
            "the lower branches of the trees."

    val groups = groupByFirstNLetters(s, 3)

    // Print version 1
    for ((prefix, words) in groups) {
        println("$prefix : $words")
    }

    println()

    // Print version 2
    for ((prefix, words) in groups) {
        println("$prefix: ${words.joinToString(", ")}")
    }
}




/*
run:

the : [the, the, the, the]
low : [lowly, lowland, lower]
inh : [inhabitants]
wer : [were]
sur : [surprised]
see : [see]
bra : [branches]
tre : [trees]

the: the, the, the, the
low: lowly, lowland, lower
inh: inhabitants
wer: were
sur: surprised
see: see
bra: branches
tre: trees

*/

 



answered Mar 13 by avibootz
...