Skip to content

Instantly share code, notes, and snippets.

@GlenDC
Last active August 29, 2015 14:01
Show Gist options
  • Save GlenDC/245d5fb6b86372eddd90 to your computer and use it in GitHub Desktop.
Save GlenDC/245d5fb6b86372eddd90 to your computer and use it in GitHub Desktop.
Combinations of an array in Go
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)
}
array := []int{1, 2, 3, 4}
combinations := AllUniqueCombinations(array)
for _, a := range combinations {
fmt.Println(a)
}
[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
Copy link

The else isn't necessary. You can make it idiomatic by:

    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)
        }
        return result
    }

    result = append(result, combination)

    return result

@GlenDC
Copy link
Author

GlenDC commented May 19, 2014

@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