Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create multidimensional Vectors in Scala?

I want to work with an immutable indexed multidimensional array. The structure that makes sense is a Vector of Vectors.

scala> val v = Vector[Vector[Int]](Vector[Int](1,2,3), Vector[Int](4,5,6), Vector[Int](7,8,9))
v: scala.collection.immutable.Vector[Vector[Int]] = Vector(Vector(1, 2, 3), Vector(4, 5, 6), Vector(7, 8, 9))

It would be nice to create an empty array just by specifying the dimensions, like you can with Array.ofDim.

scala> a = Array.ofDim[Int](3,3)
a: Array[Array[Int]] = Array(Array(0, 0, 0), Array(0, 0, 0), Array(0, 0, 0))

However, there is no Vector.ofDim, function, and I can't find an equivalent.

Is there an equivalent of Array.ofDim for immutable objects? If not, why not?

like image 214
W.P. McNeill Avatar asked Oct 12 '12 21:10

W.P. McNeill


People also ask

How do you make a multidimensional array?

You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.

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.

Can vectors be multidimensional?

For a multidimensional array, memory for the elements of the array is required to be allocated contiguously. For a vector of vector, the memory for the elements is most likely going to be disjoint. Also, it is possible to defined a vector of vectors in which the number of columns is not same for each row.


1 Answers

Each standard collection class has a companion object with factory methods, including fill. By example:

Vector.fill(3, 3)( 0 )

See the relevant scaladoc.

like image 61
Régis Jean-Gilles Avatar answered Sep 21 '22 01:09

Régis Jean-Gilles