Skip to content

Instantly share code, notes, and snippets.

@koonix
Last active October 6, 2024 17:32
Show Gist options
  • Save koonix/92208d15337ed29f12f1fd2012665e57 to your computer and use it in GitHub Desktop.
Save koonix/92208d15337ed29f12f1fd2012665e57 to your computer and use it in GitHub Desktop.
Go function that returns the permutations of a slice.
func permute[T any](v []T) [][]T {
switch len(v) {
case 0:
return [][]T{
{},
}
case 1:
return [][]T{
{v[0]},
}
}
result := make([][]T, 0, factorial(len(v)))
for i := range v {
for _, p := range permute(pop(v, i, i+1)) {
result = append(result, append([]T{v[i]}, p...))
}
}
return result
}
func factorial(n int) int {
result := 1
for i := 1; i <= n; i++ {
result *= i
}
return result
}
// pop returns a new slice that doesn't contain the elements s[i:j].
func pop[T any](s []T, i, j int) []T {
ss := make([]T, 0, len(s)-1)
ss = append(ss, s[:i]...)
ss = append(ss, s[j:]...)
return ss
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment