Efficiently extract 2-dimensional column columns in Scala

Consider a two-dimensional array, for example

scala> val a = Array.tabulate(2,3){_+_}
a: Array[Array[Int]] = Array(Array(0, 1, 2), Array(1, 2, 3))

How to define a function

def getCol(ith: Int, a: Array[Array[Int]]): Array[Int]

which provides

val col2 = getCol(2, a)
col2: Array[Int] = Array(1,2)

A simple and ineffective approach includes

def getCol(ith: Int, a: Array[Int]): Array[Int] = {
  val t = a.transpose
  t(ith)
}

Thus, to ask and more effective ways.

+4
source share
1 answer
def getCol(n: Int, a: Array[Array[Int]]) = a.map{_(n - 1)}

Note that for the Nth element you must use n - 1.

+6
source

Source: https://habr.com/ru/post/1528068/


All Articles