Home > Net >  Groovy 2D array combinations
Groovy 2D array combinations

Time:04-06

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.

CodePudding user response:

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.

CodePudding user response:

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]]
  • Related