How to print all possible permutations (all possible orderings) of the words in Kotlin

2 Answers

0 votes
fun main() {
    val words = listOf("Kotlin", "Programming", "Language")

    val permutations = words.permutations()

    for (perm in permutations) {
        //println(perm)
        println("${perm[0]}, ${perm[1]}, ${perm[2]}")
    }
}

fun <T> List<T>.permutations(): List<List<T>> {
    if (this.isEmpty()) return listOf(emptyList())
    
    val result = mutableListOf<List<T>>()
    
    for (i in this.indices) {
        val element = this[i]
        val remainingList = this.filterIndexed { index, _ -> index != i }
        for (perm in remainingList.permutations()) {
            result.add(listOf(element) + perm)
        }
    }
    
    return result
}


 
/*
run:

Kotlin, Programming, Language
Kotlin, Language, Programming
Programming, Kotlin, Language
Programming, Language, Kotlin
Language, Kotlin, Programming
Language, Programming, Kotlin
 
*/

 



answered Jan 21, 2025 by avibootz
0 votes
fun main() {
    val words = listOf("Kotlin", "Programming", "Language")
    
    val permutations = mutableListOf<List<String>>()
    
    generatePermutations(words, mutableListOf(), permutations)
    
    permutations.forEach { println(it) }
}

fun generatePermutations(words: List<String>, current: MutableList<String>, permutations: MutableList<List<String>>) {
    if (current.size == words.size) {
        permutations.add(current.toList())
        return
    }
    
    for (word in words) {
        if (!current.contains(word)) {
            current.add(word)
            generatePermutations(words, current, permutations)
            current.removeAt(current.size - 1)
        }
    }
}


 
/*
run:

[Kotlin, Programming, Language]
[Kotlin, Language, Programming]
[Programming, Kotlin, Language]
[Programming, Language, Kotlin]
[Language, Kotlin, Programming]
[Language, Programming, Kotlin]
 
*/

 



answered Jan 21, 2025 by avibootz

Related questions

...