Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

- Fix failure to generate all possible combinations (backport #3132) #3141

Merged
merged 1 commit into from
Jan 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion common/graph/choose.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,14 @@ func choose(n int, targetAmount int, i int, currentSubGroup []int, subGroups *or
return
}
// We either pick the current element
choose(n, targetAmount, i+1, append(currentSubGroup, i), subGroups)
choose(n, targetAmount, i+1, concatInts(currentSubGroup, i), subGroups)
// Or don't pick it
choose(n, targetAmount, i+1, currentSubGroup, subGroups)
}

func concatInts(a []int, elements ...int) []int {
var res []int
res = append(res, a...)
res = append(res, elements...)
return res
}
30 changes: 30 additions & 0 deletions common/graph/choose_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ SPDX-License-Identifier: Apache-2.0
package graph

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"
Expand All @@ -24,3 +25,32 @@ func TestCombinationsExceed(t *testing.T) {
// N < K returns false
require.False(t, CombinationsExceed(20, 30, 0))
}

func TestChooseKoutOfN(t *testing.T) {
expectedSets := indiceSets{
&indiceSet{[]int{0, 1, 2, 3}},
&indiceSet{[]int{0, 1, 2, 4}},
&indiceSet{[]int{0, 1, 2, 5}},
&indiceSet{[]int{0, 1, 3, 4}},
&indiceSet{[]int{0, 1, 3, 5}},
&indiceSet{[]int{0, 1, 4, 5}},
&indiceSet{[]int{0, 2, 3, 4}},
&indiceSet{[]int{0, 2, 3, 5}},
&indiceSet{[]int{0, 2, 4, 5}},
&indiceSet{[]int{0, 3, 4, 5}},
&indiceSet{[]int{1, 2, 3, 4}},
&indiceSet{[]int{1, 2, 3, 5}},
&indiceSet{[]int{1, 2, 4, 5}},
&indiceSet{[]int{1, 3, 4, 5}},
&indiceSet{[]int{2, 3, 4, 5}},
}
require.Equal(t, indiceSetsToStrings(expectedSets), indiceSetsToStrings(chooseKoutOfN(6, 4)))
}

func indiceSetsToStrings(sets indiceSets) []string {
var res []string
for _, set := range sets {
res = append(res, fmt.Sprintf("%v", set.indices))
}
return res
}