elm*_*elm 5 arrays collections scala
例如,考虑一个二维数组
scala> val a = Array.tabulate(2,3){_+_}
a: Array[Array[Int]] = Array(Array(0, 1, 2), Array(1, 2, 3))
Run Code Online (Sandbox Code Playgroud)
如何定义一个函数
def getCol(ith: Int, a: Array[Array[Int]]): Array[Int]
Run Code Online (Sandbox Code Playgroud)
提供
val col2 = getCol(2, a)
col2: Array[Int] = Array(1,2)
Run Code Online (Sandbox Code Playgroud)
一种简单而低效的方法包括
def getCol(ith: Int, a: Array[Int]): Array[Int] = {
val t = a.transpose
t(ith)
}
Run Code Online (Sandbox Code Playgroud)
因此,还要问更有效的方法.
def getCol(n: Int, a: Array[Array[Int]]) = a.map{_(n - 1)}
Run Code Online (Sandbox Code Playgroud)
请注意,您必须使用n - 1
第N个元素.