Skip to content

Instantly share code, notes, and snippets.

@tamuhey
Created June 1, 2019 08:51
Show Gist options
  • Save tamuhey/0119fc83ddbc46fce41b4af9c2d043a5 to your computer and use it in GitHub Desktop.
Save tamuhey/0119fc83ddbc46fce41b4af9c2d043a5 to your computer and use it in GitHub Desktop.
Permutations for Golang (Heap's algolithm)
package permutations
func Permutations(arr []int) <-chan []int {
var fn func([]int, int)
ch := make(chan []int)
token := make(chan struct{}, factorial(len(arr)))
fn = func(arr []int, n int) {
if n == 1 {
tmp := make([]int, len(arr))
copy(tmp, arr)
token <- struct{}{}
ch <- tmp
if len(token) == cap(token) {
close(ch)
}
} else {
for i := 0; i < n; i++ {
fn(arr, n-1)
if n%2 == 1 {
arr[i], arr[n-1] = arr[n-1], arr[i]
} else {
arr[0], arr[n-1] = arr[n-1], arr[0]
}
}
}
}
go fn(arr, len(arr))
return ch
}
func factorial(n int) int {
if n <= 1 {
return 1
}
return n * factorial(n-1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment