Google News
logo
Golang - Interview Questions
Print all permutations of a slice characters or string
Implement the perm() function that accepts a slice or string and prints all possible combinations of characters.
 
Solution
package main
import "fmt"

// Perm calls f with each permutation of a.

func Perm(a []rune, f func([]rune)) {
        perm(a, f, 0)
}

// Permute the values at index i to len(a)-1.

func perm(a []rune, f func([]rune), i int) {
        if i > len(a) {
                f(a)
                return
        }
        perm(a, f, i+1)
        for j := i + 1; j < len(a); j++ {
                a[i], a[j] = a[j], a[i]
                perm(a, f, i+1)
                a[i], a[j] = a[j], a[i]
        }
}

func main() {
Perm([]rune("abc"), func(a []rune) {
        fmt.Println(string(a))
})
}
Output : 
abc
acb
bac
bca
cba
cab
We use rune types to handle both slices and strings. Runes are Unicode code points and can therefore parse strings and slices equally.
Advertisement