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?
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.
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.
You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.
You need to iterate through loop and using fill method you can fill 2D array with one loop.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With