Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to create permutations of words without repetition 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

1 answer 99 views
1 answer 89 views
1 answer 103 views
1 answer 88 views
1 answer 89 views
2 answers 1,840 views
...