2-D arrays: working with a grid · Matrices 2D: trabajar con una cuadrícula
A grid of values
- A normal array is a single row of values.
- A 2-D array is a grid: it has rows and columns, like a table or a spreadsheet.
- We use it for game boards, images, tables of marks, and more.
Una cuadrícula de valores
- Un array normal es una única fila de valores.
- Un array 2-D es una cuadrícula: tiene filas y columnas, como una tabla o una hoja de cálculo.
- Lo usamos para tableros de juegos, imágenes, tablas de calificaciones y más.
Making a 2-D array
int[][] g = new int[3][4];makes a grid with 3 rows and 4 columns.- Every cell starts at
0(forint). - You can also fill it directly with values inside
{...}.
Crear un array 2-D
int[][] g = new int[3][4];crea una cuadrícula con 3 filas y 4 columnas.- Cada celda comienza en
0(paraint). - También puedes llenarlo directamente con valores dentro de
{...}.
public class Main {
public static void main(String[] args) {
int[][] g = new int[3][4]; // 3 rows, 4 columns, all 0
int[][] table = {
{1, 2, 3},
{4, 5, 6}
}; // 2 rows, 3 columns
System.out.println(table[0][2]); // 3
System.out.println(table[1][0]); // 4
}
}
Reading and writing one cell
- A cell needs two indexes:
g[row][col]. Row first, then column. - Both indexes start at 0.
g[1][2] = 9;stores9in row1, column2.
Leer y escribir una celda
- Una celda necesita dos índices:
g[row][col]. Fila primero, luego columna. - Ambos índices comienzan en 0.
g[1][2] = 9;almacena9en la fila1, columna2.
public class Main {
public static void main(String[] args) {
int[][] g = new int[2][2];
g[0][0] = 5;
g[0][1] = 7;
g[1][0] = 9;
g[1][1] = 11;
System.out.println(g[1][0]); // 9
g[1][0] = g[1][0] + 1;
System.out.println(g[1][0]); // 10
}
}
How big is the grid?
g.length— the number of rows.g[0].length— the number of columns in row0.- In AP CSA every row has the same length, so
g[0].lengthis the column count for the whole grid.
¿Qué tan grande es la cuadrícula?
g.length— el número de filas.g[0].length— el número de columnas en la fila0.- En AP CSA cada fila tiene la misma longitud, por lo que
g[0].lengthes el conteo de columnas para toda la cuadrícula.
public class Main {
public static void main(String[] args) {
int[][] g = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(g.length); // 2 rows
System.out.println(g[0].length); // 3 columns
}
}
Row-major traversal
- To visit every cell, use a loop inside a loop.
- The outer loop picks the row
r. The inner loop picks the columnc. - This visits row
0fully, then row1, and so on. This order is called row-major.
Recorrido en orden de filas
- Para visitar cada celda, usa un bucle dentro de otro bucle.
- El bucle externo selecciona la fila
r. El bucle interno selecciona la columnac. - Esto visita la fila
0completamente, luego la fila1, y así sucesivamente. Este orden se llama orden de filas (row-major).
public class Main {
public static void main(String[] args) {
int[][] g = {
{1, 2, 3},
{4, 5, 6}
};
int total = 0;
for (int r = 0; r < g.length; r++) {
for (int c = 0; c < g[0].length; c++) {
total = total + g[r][c];
}
}
System.out.println(total); // 21
}
}
Common mistakes
- Index a grid
grid[row][col]. grid.lengthis the number of rows;grid[0].lengthis the columns.
Errores comunes
- Indexa una cuadrícula como
grid[row][col]. grid.lengthes el número de filas;grid[0].lengthson las columnas.
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
Ahora tú intentas
- Cada tarea prellena la plantilla de la clase — escribe tu código dentro de main, o completa el método mostrado.
- Presiona Ejecutar para compilar y ejecutar, luego Verificar respuesta.
- Tu código se compila y ejecuta en el servidor, así que incluso la primera ejecución es rápida.
A 2-D array is a grid · Una matriz 2D es una cuadrícula
A 2-D array is rows × columns; reach a cell with a[row][col]. · Una matriz 2D son filas × columnas; accede a una celda con a[row][col].
Complete sumGrid(int[][] g) so it returns the total of every cell in the grid. Use a nested loop with g.length rows and g[0].length columns. · Completa sumGrid(int[][] g) para que devuelva la suma total de todas las celdas de la cuadrícula. Usa un bucle anidado con g.length filas y g[0].length columnas.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete rowSum(int[][] g, int r) so it returns the total of the cells in row · fila r only. Loop over the columns of that one row. · Completa rowSum(int[][] g, int r) para que devuelva la suma de las celdas en la fila r únicamente. Recorre las columnas de esa fila específica.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
In main, the grid is given. Print each row · fila on its own line, with the numbers joined by a single space. For the grid shown, the output is 1 2 3 then 4 5 6. (Build each line in row-major order, then println it.) · En main, se proporciona la cuadrícula. Imprime cada fila en su propia línea, con los números separados por un solo espacio. Para la cuadrícula mostrada, la salida es 1 2 3 seguido de 4 5 6. (Construye cada línea en orden mayoritario de filas, luego haz println).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.