2

With groovy I want to make a transpose on list of lists(with different sizes).

def mtrx = [
   [1,2,3],
   [4,5,6,7]
]

expected result:

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

or

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

Method .transpose() is working for equal sized is working fine, but for not equal - some elements are cut off.

My code is:

def max = 0
def map = [:]
def mapFinal = [:]
def row = 0

def mtrx = [
   [1,2,3],
   [4,5,6,7]
]

mtrx.each{it->
    println it.size()
    if(max < it.size()){
        max = it.size()
    }
}
def transposed = mtrx.each{it->
   println it
   it.eachWithIndex{it1, index->
       println it1 + ' row ' + row  + ' column ' +index
       mapFinal[row+''+index] = it1
       map[index+''+row] = it1
   }
   row++
}
println map
println mapFinal
DataScientYst
  • 442
  • 2
  • 7
  • 19

1 Answers1

6

Try

(0..<(mtrx*.size().max())).collect {
    mtrx*.getAt(it)
}
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • Thank you very much :) Groovy - never ceases to amaze me - short, groovy and working. Now I'll try to understand how it work (1) get the max by mtrx*.size().max() (2) iterate from 0 to max (3) combine closure and spread operator to get every element in column. – DataScientYst Jan 22 '17 at 16:44