Skip to content

Instantly share code, notes, and snippets.

@gdevanla
Last active August 29, 2015 13:56
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 gdevanla/8868974 to your computer and use it in GitHub Desktop.
Save gdevanla/8868974 to your computer and use it in GitHub Desktop.
//Cartesian product of input (for Integers)
//similar to itertools.product in Python
def l = [ [1,2] , [3,4] , [5, 6]]
def product(l){
def p = { l1, l2 ->
l1.inject([]) { acc, i ->
acc + l2.inject([]) { acc1, j ->
if ( i instanceof List) { acc1 << i + j}
else { acc1 << [i, j]}}}}
l.inject() { acc, it -> p(acc, it) }
}
println product(l)
//[[1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment