mike rodent
mike rodent

Reputation: 15652

Groovy: create a two-dimensional array from two ranges

I want to create this:

[ [ 1, 1 ], [ 1, 2 ], [ 1, 3 ], [ 2, 1 ] ... [ 6, 3 ]]

Using GroovyConsole I've being trying stuff like this:

def blob = (1..6).collect{ i ->
  (1..3).collect{ j ->
    [ i, j ]
  }
}
println "$blob ${blob.class.simpleName}"

... with various permutations of calls to flatten, as you might surmise.

Is there a way to achieve this?

Upvotes: 2

Views: 151

Answers (1)

ernest_k
ernest_k

Reputation: 45319

It's easier to do using the combinations method:

l1 = [1,2,3,4,5,6]
l2 = [1,2,3]
[l, l2].combinations()

Which outputs:

[[1, 1], [2, 1], [3, 1], [4, 1], [5, 1], [6, 1], [1, 2], [2, 2], 
 [3, 2], [4, 2], [5, 2], [6, 2], [1, 3], [2, 3], [3, 3], [4, 3], 
 [5, 3], [6, 3]]

Upvotes: 2

Related Questions