Contenido del Curso
Introduction to Scala
Introduction to Scala
Two-Dimensional Arrays
Up to this point, we have created and dealt only with one-dimensional array. However, like many other programming languages, Scala also supports multidimensional arrays.
Most of the time, though, programmers work with only one-dimensional and two-dimensional arrays. Three-dimensional arrays are also used but extremely rarely, and only for some very specific cases (e.g., working with images). However, you can also create n-dimensional arrays in Scala where n can be pretty large.
What is a 2D Array?
Once again, in order to work with 2D arrays, we have to understand what they actually are.
It can be easily visualized as a table or a grid consisting of rows and columns. Basically, you can think of a 2D array as a matrix with m
rows and n
columns, where m
and n
are positive integers.
Let's take a look at the general syntax of declaring a 2D array variable in Scala:
Main
var arrayName = Array.ofDim[dataType](m, n)
The ofDim
method is a method which creates an array where each element is an array itself, allowing for multiple dimensions. Once again, arrayName
is simply a variable name, dataType
is the data type of the array elements, m
and n
are the number of rows and columns, respectively.
Similarly to 1D arrays, we can declare a 2D array with predefined elements. Here's an example:
Main
var matrix = Array( Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9), Array(10, 11, 12))
Here, for our 2D array we create 4 1D arrays with 3 predefined elements, so we get a 4x3
2D array.
Indexing in 2D Arrays
Let's first take a look at the visualization of the 2D array which we created in the example above:
As you can see, the indexing in 2D arrays is similar to that of 1D arrays. Basically, rows (1D arrays) are indexed by integers from 0
to n - 1
(3
in our case), where n
is the number of rows, and columns from 0
to m - 1
(2
in our case), where m
is the number of columns.
To access a particular element in a 2D array, we have to specify its row index and column index. For instance, the element with the value of 8
in our example has 2
and 1
as its row and column indices, respectively.
Let's now take a look at the code:
Main
object Main { def main(args: Array[String]): Unit = { var matrix = Array( Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9), Array(10, 11, 12)) println(matrix(2)(1)) } }
We can also manually fill a 2D array with elements using indices:
Main
object Main { def main(args: Array[String]): Unit = { var matrix = Array.ofDim[Int](2, 2) matrix(0)(0) = 23 matrix(0)(1) = 54 matrix(1)(0) = 68 matrix(1)(1) = 10 } }
Here is how we can visualize this 2x2
2D array:
Now, it's time to test our knowledge.
¡Gracias por tus comentarios!