5

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?

1
  • matrix, as you've defined it, is a Vector[Int], not an Array[Int]. Commented Dec 19, 2014 at 7:35

4 Answers 4

11
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))
Sign up to request clarification or add additional context in comments.

Comments

8

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, ....

Comments

2

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)

Comments

1
for (x <- (0 until 10).toArray) yield (x until x + 10).toArray

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.