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.
def getCol(n: Int, a: Array[Array[Int]]) = a.map{_(n - 1)}
Note that you have to use n - 1
for Nth element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With