我有一个像这样定义的3d数组:
val 3dArray = new Array[Array[Array[Int]]](512, 8, 8)
在Javascript中,我会执行以下操作将每个元素分配给1:
for (i = 0; i < 512; i++)
{
3dArray[i] = [];
for (j = 0; j < 8; j++)
{
3dArray[i][j] = [];
for (k = 0; k < 8; k++)
{
3dArray[i][j][k] = 1;
}
}
}
最优雅的做法是什么?
答案 0 :(得分:18)
不确定是否有一种特别优雅的方式,但这是一种方式(我使用后缀s
来表示维度,即xss
是一个二维数组。)
val xsss = Array.ofDim[Int](512, 8, 8)
for (xss <- xsss; xs <- xss; i <- 0 until 8)
xs(i) = 1
或者,使用transform它会更短:
for (xss <- xsss; xs <- xss)
xs transform (_ => 1)
答案 1 :(得分:5)
for {
i <- a.indices
j <- a(i).indices
k <- a(i)(j).indices
} a(i)(j)(k) = 1
或
for {
e <- a
ee <- e
i <- ee.indices
} ee(i) = 1
答案 2 :(得分:2)
请参阅:http://www.scala-lang.org/api/current/index.html#scala.Array$
您有Array.fill将1到5维的数组初始化为某个给定值,并使用Array.tabulate初始化给定当前索引的1到5维数组:
scala> Array.fill(2,1,1)(42)
res1: Array[Array[Array[Int]]] = Array(Array(Array(42)), Array(Array(42)))
enter code here
scala> Array.tabulate(3,2,1){ (x,y,z) => x+y+z }
res2: Array[Array[Array[Int]]] = Array(Array(Array(0), Array(1)), Array(Array(1), Array(2)), Array(Array(2), Array(3)))