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 2 hours ago by avibootz

Related questions

...