Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simplest way to convert array to 2d array in scala

Tags:

arrays

scala

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?

like image 356
bourneli Avatar asked Dec 19 '14 07:12

bourneli


People also ask

How do you make a 1d array into a 2d array?

Use reshape() Function to Transform 1d Array to 2d Array The number of components within every dimension defines the form of the array. We may add or delete parameters or adjust the number of items within every dimension by using reshaping. To modify the layout of a NumPy ndarray, we will be using the reshape() method.

Which function is used to define a single dimension or multiple dimension array in Scala programming language?

Scala has a method Array. ofDim to create a multidimensional array. This approach can be used to create arrays of up to five dimensions.

What is the difference between list and array in Scala?

Following are the point of difference between lists and array in Scala: Lists are immutable whereas arrays are mutable in Scala. Lists represents a linked list whereas arrays are flat.


1 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))
like image 184
Chris Martin Avatar answered Sep 22 '22 05:09

Chris Martin