Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created August 8, 2014 14:24
Show Gist options
  • Save bdkosher/ff707c2428543e5f3c81 to your computer and use it in GitHub Desktop.
Save bdkosher/ff707c2428543e5f3c81 to your computer and use it in GitHub Desktop.
Closure for returning the combinations of the input list of the provided size, r
// returns combinations of the input list of the provided size, r
def combinationsOf = { List list, int r ->
assert (0..<list.size()).contains(r)
def combs = [] as Set
list.eachPermutation {
combs << it.subList(0, r).sort { a, b -> a <=> b }
}
combs as List
}
assert combinationsOf([1, 2, 3], 2) == [[1, 2], [1, 3], [2, 3]]
assert combinationsOf([1, 2, 3, 4], 2) == [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
assert combinationsOf([1, 2, 3, 4], 3) == [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment