Skip to content

Instantly share code, notes, and snippets.

@oludouglas
Created September 23, 2020 09:01
Show Gist options
  • Save oludouglas/f2b312d57ddcd5ee3cd595d1f90cfa38 to your computer and use it in GitHub Desktop.
Save oludouglas/f2b312d57ddcd5ee3cd595d1f90cfa38 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
// tested on plaground at https://play.golang.org/p/j3fBcTmAx37
// Permutation calls f with each permutation of a.
func Permutation(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() {
Permutation([]rune("TURING"), func(a []rune) {
fmt.Println(string(a))
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment