The simplest way to convert an array to a 2d array in scala

I have 10 and times; 10Array[Int]

val matrix = for {
    r <- 0 until 10
    c <- 0 until 10
} yield r + c  

and want to convert the "matrix" to Array[Array[Int]]with 10 rows and 10 columns.

What is the easiest way to do this?

+4
source share
4 answers
val matrix = (for {
    r <- 0 until 3
    c <- 0 until 3
} yield r + c).toArray
// Array(0, 1, 2, 1, 2, 3, 2, 3, 4)

scala> matrix.grouped(3).toArray
// Array(Array(0, 1, 2), Array(1, 2, 3), Array(2, 3, 4))
+10
source

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 [Int] array 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, ....
+7
source

, , Int, . Vector ,

val matrix = for (r <- 1 to 10)
  yield for(c <- 1 to 10)
    yield r+c

[Array [Int]], , , chris-martin

matrix.grouped(10).toArray.map(_.toArray)
+2
for (x <- (0 until 10).toArray) yield (x until x + 10).toArray
+1

Source: https://habr.com/ru/post/1568273/


All Articles