Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Function to compute k-Combinations of a list
List kCombinations(List l, Integer k) {
assert k >= 0, 'Invalid "k"'
if (l.empty || !k) []
else if (k == 1) l.collate(1)
else
(0..l.size()-1).inject([] as Set) { acc, i ->
def c = kCombinations(l.drop(i+1), k-1)
acc + [l[i], c].combinations { cn ->
def cnf = cn.flatten()
cnf.size() == k ? cnf : [l[i],c].flatten()
}
}.toList()
}
assert kCombinations(1..4, 3).size() == 4
assert kCombinations(1..14, 4).size() == 1001
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment