How to generate all possible permutations and combinations of an array of chars in Swift

1 Answer

0 votes
import Foundation

// Swap two elements in an array
func swap(_ arr: inout [Character], _ i: Int, _ j: Int) {
    let tmp = arr[i]
    arr[i] = arr[j]
    arr[j] = tmp
}

// Print array of characters
func printArray(_ arr: [Character]) {
    print(arr.map { String($0) }.joined(separator: " "))
}

// Recursive function to generate permutations
func permute(_ arr: inout [Character], _ 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
func generateCombinations(_ arr: [Character]) {
    let size = arr.count
    for mask in 1..<(1 << size) {
        var combo: [Character] = []
        for i in 0..<size {
            if (mask & (1 << i)) != 0 {
                combo.append(arr[i])
            }
        }
        print(combo.map { String($0) }.joined(separator: " "))
    }
}

func main() {
    var input: [Character] = Array("abc")
    let size = input.count

    print("All permutations:")
    permute(&input, 0, size - 1)

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

main()



/*
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

...