Last active
August 29, 2015 14:01
-
-
Save GlenDC/245d5fb6b86372eddd90 to your computer and use it in GitHub Desktop.
Combinations 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 AllUniqueCombinations_Recursive(combination, array []int, result [][]int) [][]int { | |
if len(array) > 0 { | |
for i := range array { | |
c := make([]int, 0, len(combination)) | |
c = append(c, combination...) | |
c = append(c, array[i]) | |
a := make([]int, 0, len(array)-1) | |
a = append(a, array[0:i]...) | |
a = append(a, array[i+1:]...) | |
result = AllUniqueCombinations_Recursive(c, a, result) | |
} | |
} | |
result = append(result, combination) | |
return result | |
} | |
func AllUniqueCombinations(array []int) [][]int { | |
return AllUniqueCombinations_Recursive(nil, array, nil) | |
} |
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, 4} | |
combinations := AllUniqueCombinations(array) | |
for _, a := range combinations { | |
fmt.Println(a) | |
} |
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 3 4] | |
[1 2 4 3] | |
[1 3 2 4] | |
[1 3 4 2] | |
[1 4 2 3] | |
[1 4 3 2] | |
[2 1 3 4] | |
[2 1 4 3] | |
[2 3 1 4] | |
[2 3 4 1] | |
[2 4 1 3] | |
[2 4 3 1] | |
[3 1 2 4] | |
[3 1 4 2] | |
[3 2 1 4] | |
[3 2 4 1] | |
[3 4 1 2] | |
[3 4 2 1] | |
[4 1 2 3] | |
[4 1 3 2] | |
[4 2 1 3] | |
[4 2 3 1] | |
[4 3 1 2] | |
[4 3 2 1] |
@hariharan-uno thank you, I applied this. It's a simple, yet nice improvement!
But as I was new to go I was wondering if there were things I could improve regarding my slice usage, etc...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The else isn't necessary. You can make it idiomatic by: