2022-01-25 21:43:10 +00:00
|
|
|
/*
|
|
|
|
Package permutation implements Heap's algorithm for generating permutations of
|
|
|
|
lists. It uses Go 1.18's new generics feature to provide a generic interface
|
|
|
|
*/
|
2022-01-21 21:12:47 +00:00
|
|
|
package permutation
|
|
|
|
|
2022-01-25 21:43:10 +00:00
|
|
|
// GenSlice is a generic slice of data
|
2022-01-21 21:12:47 +00:00
|
|
|
type GenSlice[T any] []T
|
|
|
|
|
2022-01-25 21:43:10 +00:00
|
|
|
/*
|
|
|
|
Permutations uses Heap's Algorithm to generate a list of all possible
|
|
|
|
permutations of the provided list. Most slices will automatically coerce
|
|
|
|
their type into a GenSlice[T] with no casting required
|
|
|
|
*/
|
2022-01-21 21:12:47 +00:00
|
|
|
func Permutations[T any](arr GenSlice[T]) []GenSlice[T] {
|
|
|
|
var helper func(GenSlice[T], int)
|
|
|
|
var res []GenSlice[T]
|
|
|
|
|
|
|
|
helper = func(arr GenSlice[T], n int) {
|
|
|
|
if n == 1 {
|
|
|
|
var tmp GenSlice[T]
|
|
|
|
for _, i := range arr {
|
|
|
|
tmp = append(tmp, i)
|
|
|
|
}
|
|
|
|
res = append(res, tmp)
|
|
|
|
} else {
|
|
|
|
for i := 0; i < n; i++ {
|
|
|
|
helper(arr, n-1)
|
|
|
|
if n%2 == 1 {
|
|
|
|
tmp := arr[i]
|
|
|
|
arr[i] = arr[n-1]
|
|
|
|
arr[n-1] = tmp
|
|
|
|
} else {
|
|
|
|
tmp := arr[0]
|
|
|
|
arr[0] = arr[n-1]
|
|
|
|
arr[n-1] = tmp
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
helper(arr, len(arr))
|
|
|
|
return res
|
|
|
|
}
|