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,926 questions

51,859 answers

573 users

How to generate all possible permutations and combinations of a slice of chars in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

// Swap two elements in a slice
func swap(arr []rune, i, j int) {
    arr[i], arr[j] = arr[j], arr[i]
}

// Print slice of runes
func printArray(arr []rune) {
    for _, ch := range arr {
        fmt.Printf("%c ", ch)
    }
    fmt.Println()
}

// Recursive function to generate permutations
func permute(arr []rune, l, r int) {
    if l == r {
        printArray(arr)
        return
    }
    for i := l; i <= r; i++ {
        swap(arr, l, i)
        permute(arr, l + 1, r)
        swap(arr, l, i) // backtrack
    }
}

// Generate all combinations using bitmask
func generateCombinations(arr []rune) {
    size := len(arr)
    for mask := 1; mask < (1 << size); mask++ {
        for i := 0; i < size; i++ {
            if mask & (1 << i) != 0 {
                fmt.Printf("%c ", arr[i])
            }
        }
        fmt.Println()
    }
}

func main() {
    input := []rune("abc")
    size := len(input)

    fmt.Println("All permutations:")
    permute(input, 0, size-1)

    fmt.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

...