Last active
August 29, 2015 14:01
-
-
Save GlenDC/d745e6fd51f7589d8e2e to your computer and use it in GitHub Desktop.
Permations of an array in Go
This file contains 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
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 | |
} |
This file contains 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
array := []int{1, 2, 3} | |
permutations := Permutations(array) | |
for _, p := range permutations { | |
fmt.Println(p) | |
} |
This file contains 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
[] | |
[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