Skip to content

Instantly share code, notes, and snippets.

@soyart
Created October 1, 2024 18:37
Show Gist options
  • Select an option

  • Save soyart/1186a5a61a3e4e82dbbf4864b199aa83 to your computer and use it in GitHub Desktop.

Select an option

Save soyart/1186a5a61a3e4e82dbbf4864b199aa83 to your computer and use it in GitHub Desktop.
All permutations
package main
import (
"fmt"
)
func main() {
r := permutation([]byte("abcdef"))
for i := range r {
pront(r[i])
}
}
func pront(s []byte) {
for i := range s {
fmt.Printf("%c", s[i])
}
fmt.Printf("\n")
}
func factorial(i int) int {
switch i {
case
0,
1:
return 1
case 2:
return 2
}
return i * factorial(i-1)
}
func swap[T any](s []T, i, j int) {
s[i], s[j] = s[j], s[i]
}
/*
1 2 3 4 swap(0, 0)
1 2 3 4 swap(0, 1)
2 1 3 4 swap(0, 2)
3 1 2 4 swap(0, 3)
4 1 2 3
*/
func permutation[T any](s []T) [][]T {
l := len(s)
switch l {
case 0:
return [][]T{}
case 1:
return [][]T{
{s[0]},
}
case 2:
return [][]T{
{s[0], s[1]},
{s[1], s[0]},
}
}
results := make([][]T, factorial(l))
c := 0
for i := range s {
swap(s, 0, i)
p := s[0]
tails := permutation(s[1:])
for j := range tails {
tails[j] = append([]T{p}, tails[j]...)
results[c] = tails[j]
c++
}
swap(s, 0, i)
}
return results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment