Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - Most elegant way of initialising values inside array that's already been declared?

Tags:

scala

I have a 3d array defined like so:

val 3dArray = new Array[Array[Array[Int]]](512, 8, 8)

In Javascript I would do the following to assign each element to 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;
        }
    }
}

What's the most elegant approach to doing the same?

like image 302
Dominic Bou-Samra Avatar asked Sep 03 '11 11:09

Dominic Bou-Samra


1 Answers

Not sure there's a particularly elegant way to do it, but here's one way (I use suffix s to indicate dimension, i.e. xss is a two-dimensional array).

val xsss = Array.ofDim[Int](512, 8, 8)
for (xss <- xsss; xs <- xss; i <- 0 until 8) 
  xs(i) = 1

Or, using transform it gets even shorter:

for (xss <- xsss; xs <- xss)
  xs transform (_ => 1)
like image 74
Martin Odersky Avatar answered Sep 20 '22 16:09

Martin Odersky