I have a 10 × 10 Array[Int]
val matrix = for {
r <- 0 until 10
c <- 0 until 10
} yield r + c
and want to convert the "matrix" to an Array[Array[Int]] with 10 rows and 10 columns.
What is the simplest way to do it?
If I understand correctly, you can do :
Array.tabulate(10,10)(_+_)
//> res0: Array[Array[Int]] = Array(Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), ....)
If you just need a 10 x 10 Array[Int] without any values you can do,
Array.ofDim[Int](10,10)
/> res1: Array[Array[Int]] = Array(Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0
//| , 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Array(0, ....
The code you showed gives you a Vector of Int, not an Array. If Vector and it is okay to generate a new you just need to yield twice
val matrix = for (r <- 1 to 10)
yield for(c <- 1 to 10)
yield r+c
If you need to convert the existing Vector to Array[Array[Int]] as you said, use grouped as chris-martin suggested
matrix.grouped(10).toArray.map(_.toArray)
matrix, as you've defined it, is aVector[Int], not anArray[Int].