Last active
August 29, 2015 14:10
-
-
Save bahmanm/3229c2d31af11ff12648 to your computer and use it in GitHub Desktop.
Function to compute k-Combinations of a list
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
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