-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheappermutations.go
More file actions
40 lines (33 loc) · 1.01 KB
/
heappermutations.go
File metadata and controls
40 lines (33 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Copyright (c) 2024 Nicolas Perraud <np bitbox io>
// The heappermutations package a generic primitive to generate all possible
// permutations following Heap's algorithm on typed collection.
package heappermutations
// Permute returns all permutations of a slice
func Permute[T any](arr []T) [][]T {
return heapPermutations(arr)
}
// An implementation of Heap's algorithm
func heapPermutations[T any](arr []T) [][]T {
var permutations [][]T
var generatePermutations func(int, []T)
generatePermutations = func(n int, a []T) {
if n == 1 {
// Create a copy of the array to avoid modifying the original slice
temp := make([]T, len(a))
copy(temp, a)
permutations = append(permutations, temp)
return
}
for i := 0; i < n; i++ {
generatePermutations(n-1, a)
// Swap elements if n is even, otherwise swap the first and last element
if n%2 == 0 {
a[i], a[n-1] = a[n-1], a[i]
} else {
a[0], a[n-1] = a[n-1], a[0]
}
}
}
generatePermutations(len(arr), arr)
return permutations
}