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.
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
{...}.
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.
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.
행 우선 순회
- 모든 셀을 방문하려면 루프 안에 루프를 사용하세요.
- 바깥쪽 루프가 행
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 버튼을 눌러 컴파일하고 실행한 후, 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입니다. (행 우선 순서로 각 줄을 만든 후 println하세요.)
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.