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 generate all possible permutations and combinations of an array of chars in Kotlin

1 Answer

0 votes
fun swap(arr: CharArray, i: Int, j: Int) {
    val tmp = arr[i]
    arr[i] = arr[j]
    arr[j] = tmp
}

fun printArray(arr: CharArray) {
    println(arr.joinToString(" "))
}

// Recursive function to generate permutations
fun permute(arr: CharArray, l: Int, r: Int) {
    if (l == r) {
        printArray(arr)
        return
    }
    for (i in l..r) {
        swap(arr, l, i)
        permute(arr, l + 1, r)
        swap(arr, l, i) // backtrack
    }
}

// Generate all combinations using bitmask
fun generateCombinations(arr: CharArray) {
    val size = arr.size
    for (mask in 1 until (1 shl size)) {
        val combo = mutableListOf<Char>()
        for (i in 0 until size) {
            if ((mask and (1 shl i)) != 0) {
                combo.add(arr[i])
            }
        }
        println(combo.joinToString(" "))
    }
}

fun main() {
    val input = charArrayOf('a', 'b', 'c')
    val size = input.size

    println("All permutations:")
    permute(input.copyOf(), 0, size - 1)

    println("\nAll combinations:")
    generateCombinations(input)
}




/*
run:

All permutations:
a b c
a c b
b a c
b c a
c b a
c a b

All combinations:
a
b
a b
c
a c
b c
a b c

*/

 



answered Nov 22, 2025 by avibootz

Related questions

...