Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient 2 dimensional array column extraction in Scala

Consider a 2 dimensional Array, for instance

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]

that delivers

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

A simple and inefficient approach includes

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

Thus to ask also for more efficient ways.

like image 433
elm Avatar asked Feb 21 '14 10:02

elm


1 Answers

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

Note that you have to use n - 1 for Nth element.

like image 75
senia Avatar answered Sep 27 '22 21:09

senia