2

我正在研究 Scala 中的多维数组,并遇到了一些创建多维数组的简单方法。即:

val my3DimensionalArray = Array.ofDim[Int](3,4,5) //array with dimensions 3 x 4 x 5

甚至

val myFilledArray = Array.fill[Int](3,4,5)(0) //Array of same dimension filled with 0's

但是,这仅适用于 1 - 5 维数组:

val my6DimensionalArray = Array.ofDim[Int](3,3,3,3,3,3) //Error

那么人们通常如何处理创建更高维度的阵列呢?这是留给第 3 方库来实现,还是 Scala 鼓励我们使用其他数据结构来代替高维数组?

4

2 回答 2

3
// create array of 5-dim-array => 6 dim array
Array.tabulate(3)(_ => Array.ofDim[Int](3,3,3,3,3)) 

Array.ofDim实现使用这个这个模式。见https://github.com/scala/scala/blob/v2.11.6/src/library/scala/Array.scala#L216-234

于 2015-06-03T14:42:21.147 回答
2

如果您真的想要任意数量的维度,您通常使用单个平面数组和第二个数组,该数组按维度索引以获取您想要的元素。所以,例如,

class MultiArray(dims: Array[Int]) {
  private val array = new Array[Double](dims.product)
  private def arrayIndex(index: Array[Int]) = {
    var i = index.length - 1
    var k = index(i)
    var n = 1
    while (i > 0) {
      n *= dims(i)
      k += n * index(i-1)
      i -= 1
    }
    k
  }
  def apply(index: Array[Int]) = array(arrayIndex(index))
  def update(index: Array[Int], value: Double) {
    array(arrayIndex(index)) = value
  }
}

would be a start. There are various mathematics libraries that do this sort of thing (IIRC Apache Commons Math does I can't quickly find a Java mathematics library that does, but ImgLib2 uses similar techniques for image data (they do local chunking also)). It's not really a generally useful thing to do, which is why you tend to find it in maths libraries.

于 2015-06-03T18:50:20.440 回答