Mykyta Hupalo
Mykyta Hupalo

Reputation: 3

Groovy 2D array combinations

I have a 2D array which looks like [[1, 2, 3], [10, 11]]. I want to get the next combinations: [[1, 2, 3, 10], [1, 2, 3, 11]]. The idea is to take all values from left array and combine it with each value from right array. I've tried different Groovy out of the box methods like combinations(), permutations() to get the expected result, but without any success. Please, help.

Upvotes: 0

Views: 422

Answers (2)

injecteer
injecteer

Reputation: 20699

Why not simply:

def a = [[1, 2, 3], [10, 11]]

def res = a[ 1 ].collect{ a[ 0 ] + it }

assert res == [[1, 2, 3, 10], [1, 2, 3, 11]]

Upvotes: 1

ernest_k
ernest_k

Reputation: 45319

If one can cheat... Nesting the first list into another list can let us use .combinations() still:

def a = [[[1, 2, 3]], [10, 11]] //a[0] changed to [a[0]]
a.combinations().collect{it.flatten()} //[[1, 2, 3, 10], [1, 2, 3, 11]]

Now, if you can't store the values like that, you can still still make the change part of your code. All this assumes that the list is just a pair.

([a[0]] + a[1..<(a.size())]).combinations().collect{it.flatten()} //same result

I believe there are less unorthodox ways of doing it, but that's a quick and dirty solution.

Upvotes: 0

Related Questions