2-D arrays: working with a grid · Arrays 2-D: trabalhando com uma grade
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.
Uma grade de valores
- Um array normal é uma única linha de valores.
- Um array 2-D é uma grade: tem linhas e colunas, como uma tabela ou planilha.
- Usamos para tabuleiros de jogos, imagens, tabelas de notas e mais.
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
{...}.
Criando um array 2-D
int[][] g = new int[3][4];cria uma grade com 3 linhas e 4 colunas.- Cada célula começa com
0(paraint). - Você também pode preenchê-la diretamente com 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.
Lendo e escrevendo uma célula
- Uma célula precisa de dois índices:
g[row][col]. Linha primeiro, depois coluna. - Ambos os índices começam em 0.
g[1][2] = 9;armazena9na linha1, coluna2.
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.
Qual é o tamanho da grade?
g.length— o número de linhas.g[0].length— o número de colunas na linha0.- Na AP CSA, todas as linhas têm o mesmo comprimento, então
g[0].lengthé a contagem de colunas para toda a grade.
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.
Percurso em ordem de linhas
- Para visitar todas as células, use um loop dentro de outro loop.
- O loop externo seleciona a linha
r. O loop interno seleciona a colunac. - Isso visita a linha
0completamente, depois a linha1, e assim por diante. Essa ordem é chamada de 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.
Erros comuns
- Indexe uma grade
grid[row][col]. grid.lengthé o número de linhas;grid[0].lengthsão as colunas.
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.
Agora você tenta
- Cada tarefa pré-preenche a estrutura da classe — escreva seu código dentro do main, ou complete o método mostrado.
- Pressione Run para compilar e executar, depois Check answer.
- Seu código compila e roda no servidor, então até a primeira execução é rápida.
A 2-D array is a grid · Um array 2-D é uma grade
A 2-D array is rows × columns; reach a cell with a[row][col]. · Um array 2-D é linhas × colunas; acesse uma célula com a[linha][coluna].
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. · Complete sumGrid(int[][] g) para que ele retorne o total de todas as células na grade. Use um laço aninhado com g.length linhas e g[0].length colunas.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete rowSum(int[][] g, int r) so it returns the total of the cells in row r only. Loop over the columns of that one row. · Complete rowSum(int[][] g, int r) para que ele retorne o total das células na linha r apenas. Itere sobre as colunas dessa única linha.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
In main, the grid is given. Print each row 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.) · Em main, a grade é dada. Imprima cada linha em sua própria linha, com os números separados por um único espaço. Para a grade mostrada, a saída é 1 2 3 então 4 5 6. (Construa cada linha em ordem linear, depois faça println.)
Click Run to see the output here. · Clique em Executar para ver a saída aqui.