Skip to content

Instantly share code, notes, and snippets.

@GlenDC
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GlenDC/d745e6fd51f7589d8e2e to your computer and use it in GitHub Desktop.
Save GlenDC/d745e6fd51f7589d8e2e to your computer and use it in GitHub Desktop.
Permations of an array in Go
func Pow(x, n int) int {
return int(math.Pow(float64(x), float64(n)))
}
func Permutations(array []int) [][]int {
size := len(array)
total := Pow(2, size)
permutations := make([][]int, 0, total)
for i := 0; i < total; i++ {
permutation := make([]int, 0, size)
for j := 0; j < size; j++ {
if Pow(2, j)&i != 0 {
permutation = append(permutation, array[j])
}
}
permutations = append(permutations, permutation)
}
return permutations
}
array := []int{1, 2, 3}
permutations := Permutations(array)
for _, p := range permutations {
fmt.Println(p)
}
[]
[1]
[2]
[1 2]
[3]
[1 3]
[2 3]
[1 2 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment