013_2 차원 배열

Dec 15, 2023
013_2 차원 배열

2 차원 배열

  • 배열과 같이 많은 데이터를 하나로 묶어서 처리하지만 ‘1 차원’이 아니라 ‘2 차원’으로 저장을 한다.
  • 배열과 같이 공간을 늘릴 수 없지만 값의 변경은 가능하다. ( 구조 변경이 불가능 하다. )

래그드 배열

  • 2 차원 배열에서 행마다 길이가 다른 배열을 말한다.

기본 구조

int[][] s = new int[3][5]; // 앞은 행 뒤는 열
💡
누적 코드 : 자기 자신에 자신의 값을 넣는 것
리펙토리 : 코드를 깔끔하게 정리 하는 것
2 차원 배열 예제
package ex03; // 2차원 배열 예제 public class TheaterSeats { public static void main(String[] args) { // 배열은 구조 변경 불가능 int[][] seats = { {0, 0, 0, 1, 1, 0, 0, 0, 0, 0}, {0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 1, 1, 0}, {1, 1, 0, 0, 0, 0, 1, 1, 1, 0} }; int sum = 0; int count = 0; //int row = -1; for (int row = 0; row < seats.length; row++) { count = 0; for (int i = 0; i < seats[row].length; i++) { count = count + seats[row][i]; } System.out.println(row + "번째 행의 관객수는: " + count); sum = sum + count; } System.out.println("전체 관계수는: " + sum); } }
출력 결과
notion image
💡
모듈화 및 단계 과정이 존재 하는 이유는 코딩 할 때 반복 해야 하는 상황을 대비하여 모듈화(일관성 있게 코드를 변경)를 진행하며 단계 과정은 순차적으로 코드를 파악해야 쉽게 모듈화를 가능하기에 진행한다.
2 차원 배열 예제 모듈화 과정
// 모듈화 및 단계 과정 - 앞의 코드에 대입해서 사용 가능하다. row++; count = 0; for (int i = 0; i < seats[row].length; i++) { count = count + seats[row][i]; } System.out.println(row + "번째 행의 관객수는: " + count); sum = sum + count; row++; count = 0; for (int i = 0; i < seats[row].length; i++) { count = count + seats[row][i]; } System.out.println(row + "번째 행의 관객수는: " + count); sum = sum + count; row++; count = 0; for (int i = 0; i < seats[row].length; i++) { count = count + seats[row][i]; } System.out.println(row + "번째 행의 관객수는: " + count); sum = sum + count; row++; count = 0; for (int i = 0; i < seats[row].length; i++) { count = count + seats[row][i]; } System.out.println(row + "번째 행의 관객수는: " + count); sum = sum + count; System.out.println("전체 관계수는: " + sum);
래그드 배열 1번 예제
package ex03; /** * 레그드 배열 * 2차원 배열에서 행마다 길이가 다른 배열을 말한다. */ public class RaggedArray { public static void main(String[] args) { int[][] ragged = new int[3][]; // 행이될 배열을 선언 ragged[0] = new int[1]; // 행마다 배열의 크기를 지정 ragged[1] = new int[2]; ragged[2] = new int[3]; for (int i = 0; i < ragged.length; i++) { for (int j = 0; j < ragged[i].length; j++) { ragged[i][j] = j; System.out.print(ragged[i][j] + " "); } System.out.println(); } } }
출력 결과
notion image
래그드 배열 2번 예제
package ex03; import java.util.Arrays; public class RaggedArray2 { public static void main(String[] args) { int[][] rarray = new int[3][]; rarray[0] = new int[]{1, 2, 3, 4}; rarray[1] = new int[]{5, 6, 7}; rarray[2] = new int[]{8, 9}; for (int i = 0; i < rarray.length; i++) { // 전통 방식으로 값을 출력 for (int j = 0; j < rarray[i].length; j++) { System.out.print(rarray[i][j] + " "); } System.out.println(); } for (int[] row : rarray) { // 1 차원 배열이면 이러한 방식으로 가능하지만 2차원 배열은 불가능하다 System.out.println(Arrays.toString(row)); } } }
출력 결과
notion image
Share article
RSSPowered by inblog