Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create and populate two-dimensional array in Scala

What's the recommended way of creating a pre-populated two-dimensional array in Scala? I've got the following code:

val map = for {
    x <- (1 to size).toList
} yield for {
        y <- (1 to size).toList
    } yield (x, y)

How do I make an array instead of list? Replacing .toList with .toArray doesn't compile. And is there a more concise or readable way of doing this than the nested for expressions?

like image 964
asteinlein Avatar asked Mar 22 '10 22:03

asteinlein


People also ask

How do you create an array of two-dimensional?

To create an array use the new keyword, followed by a space, then the type, and then the number of rows in square brackets followed by the number of columns in square brackets, like this new int[numRows][numCols] . The number of elements in a 2D array is the number of rows times the number of columns.

What is multidimensional array in Scala?

Multidimensional array is an array which store data in matrix form. You can create from two dimensional to three, four and many more dimensional array according to your need. Below we have mentioned array syntax. Scala provides an ofDim method to create multidimensional array.

Can you add to a 2D array?

You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.

Can we use arrays fill on 2D array?

You need to iterate through loop and using fill method you can fill 2D array with one loop.


1 Answers

On Scala 2.7, use Array.range:

for {
  x <- Array.range(1, 3)
} yield for {
  y <- Array.range(1, 3)
} yield (x, y)

On Scala 2.8, use Array.tabulate:

Array.tabulate(3,3)((x, y) => (x, y))
like image 185
Daniel C. Sobral Avatar answered Nov 07 '22 05:11

Daniel C. Sobral