Created
December 13, 2019 04:38
-
-
Save kingishb/1fb73c2e4cc85f63bec9f23fdb4e26dd to your computer and use it in GitHub Desktop.
gen permutations with heap's algorithm - https://en.wikipedia.org/wiki/Heap%27s_algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import "fmt" | |
| // swap swaps elements in a slice | |
| func swap(i, j int, slice []int) { | |
| v1 := slice[i] | |
| v2 := slice[j] | |
| slice[i] = v2 | |
| slice[j] = v1 | |
| } | |
| // permute generates permutations by heap's algorithm. | |
| // https://en.wikipedia.org/wiki/Heap%27s_algorithm | |
| func permutations(n int, ints []int) { | |
| if n == 1 { | |
| fmt.Println(ints) | |
| } else { | |
| for i := 0; i < n; i++ { | |
| permutations(n-1, ints) | |
| if n%2 == 0 { | |
| swap(i, n-1, ints) | |
| } else { | |
| swap(0, n-1, ints) | |
| } | |
| } | |
| } | |
| } | |
| func main() { | |
| permutations(3, []int{1, 2, 3}) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment