2-D arrays: working with a grid · Массивы 2-мерности: работа с сеткой
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.
Сетка значений
- Обычный массив — это одна строка значений.
- Двумерный 2-D массив — это сетка: у него есть строки и столбцы, как в таблице или электронной таблице.
- Мы используем его для игровых досок, изображений, таблиц оценок и многого другого.
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
{...}.
Создание 2-D массива
int[][] g = new int[3][4];создаёт сетку с 3 строками и 4 столбцами.- Каждая ячейка начинается с
0(дляint). - Также можно заполнить его напрямую значениями внутри
{...}.
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.
Чтение и запись одной ячейки
- Ячейке нужны два индекса:
g[row][col]. Сначала строка, потом столбец. - Оба индекса начинаются с 0.
g[1][2] = 9;хранит ⟨9⟩ в строке1, столбце2.
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.
Каков размер сетки?
g.length— количество строк.g[0].length— количество столбцов в строке0.- В AP CSA каждая строка имеет одинаковую длину, поэтому
g[0].lengthявляется количеством столбцов для всей сетки.
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.
Обход по строкам (row-major)
- Чтобы посетить каждую ячейку, используйте цикл внутри цикла.
- Внешний цикл выбирает строку
r. Внутренний цикл выбирает столбецc. - Это полностью посещает строку
0, затем строку1и так далее. Этот порядок называется обходом по строкам.
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.
Распространенные ошибки
- Индексируйте сетку
grid[row][col]. grid.length— количество строк;grid[0].length— количество столбцов.
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.
Теперь попробуйте сами
- Каждая задача заранее заполняет каркас класса — напишите свой код внутри main или дополните показанный метод.
- Нажмите Run (Выполнить), чтобы скомпилировать и запустить, затем Check answer (Проверить ответ).
- Ваш код компилируется и выполняется на сервере, поэтому даже первый запуск происходит быстро.
A 2-D array is a grid · Массив 2-мерности — это сетка
A 2-D array is rows × columns; reach a cell with a[row][col]. · Массив 2-мерности имеет размер строки × столбца; обратитесь к ячейке через 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. · Допишите sumGrid(int[][] g), чтобы он возвращал сумму всех ячеек в сетке. Используйте вложенный цикл со g.length строками и g[0].length столбцами.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
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. · Допишите rowSum(int[][] g, int r), чтобы он возвращал сумму ячеек только в строке r. Обходите столбцы этой одной строки.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
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.) · В main задана сетка. Выведите каждую строку на отдельной строке, соединяя числа одним пробелом. Для показанной сетки вывод будет 1 2 3, затем 4 5 6. (Создавайте каждую строку в порядке major-行, затем выводите её.)
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.