Creating and populating a two-dimensional array in Scala

What is the recommended way to create a pre-populated two-dimensional array in Scala? I have the following code:

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

How to create an array instead of a list? Replacing .toList with .toArray does not compile. And is there a more concise or readable way to do this than nested expressions?

+7
arrays scala scala-collections
source share
2 answers

In Scala 2.7 use Array.range :

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

In Scala 2.8, use Array.tabulate :

 Array.tabulate(3,3)((x, y) => (x, y)) 
+9
source share

Among other ways you can use Array.range and map :

 scala> Array.range(0,3).map(i => Array.range(0,3).map(j => (i,j))) res0: Array[Array[(Int, Int)]] = Array(Array((0,0), (0,1), (0,2)), Array((1,0), (1,1), (1,2)), Array((2,0), (2,1), (2,2))) 

Or you can use Array.fromFunction :

 scala> Array.fromFunction((i,j) => (i,j))(3,3) res1: Array[Array[(Int, Int)]] = Array(Array((0,0), (0,1), (0,2)), Array((1,0), (1,1), (1,2)), Array((2,0), (2,1), (2,2))) 

Scala 2.8 gives you even more options - view the Array object. (Actually, this is good advice for 2.7, also ....)

+2
source share

All Articles