groovy transpose 2d array different sizes

雨燕双飞 提交于 2019-12-22 11:29:07

问题


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

回答1:


Try

(0..<(mtrx*.size().max())).collect {
    mtrx*.getAt(it)
}


来源:https://stackoverflow.com/questions/41784018/groovy-transpose-2d-array-different-sizes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!