Skip to content

Instantly share code, notes, and snippets.

@bahmanm
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bahmanm/3229c2d31af11ff12648 to your computer and use it in GitHub Desktop.
Save bahmanm/3229c2d31af11ff12648 to your computer and use it in GitHub Desktop.
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