JAVA/JAVA 기초

[JAVA 기초] 다차원 배열

큐범 2021. 8. 3. 13:52

2차원 배열의 선언과 인덱스

 

선언방법 선언 예
타입[][] 변수이름; int[][] score;
타입 변수이름[][]; int score[][];
타입[] 변수이름[]; int[] score[];

2차원 배열의 초기화

int[][] arr = new int[][] { {1,2,3},{4,5,6} };

int[][] arr = { {1,2,3}, {4,5,6} };

2차원 배열의 합 구하기

package Array;

public class ArrayEx18 {

	public static void main(String[] args) {
		int[][] score = {
							{100,100,100},
							{20,20,20},
							{30,30,30},
							{40,40,40}
		};
		int sum =0;
		
		for(int i=0; i<score.length; i++) {
			for(int j=0; j<score[i].length; j++) {
				System.out.printf("score[%d] [%d] = %d%n", i,j,score[i][j]);
			}
		}
		
		for(int[] tmp : score) {
			for(int i : tmp) {
				sum += i;
			}
		}
		
		System.out.println("sum="+sum);
		
	}

}
//결과
score[0] [0] = 100
score[0] [1] = 100
score[0] [2] = 100
score[1] [0] = 20
score[1] [1] = 20
score[1] [2] = 20
score[2] [0] = 30
score[2] [1] = 30
score[2] [2] = 30
score[3] [0] = 40
score[3] [1] = 40
score[3] [2] = 40
sum=570
package Array;

public class ArrayEx19 {

	public static void main(String[] args) {
		int[][] score = {
				{100,100,100},
				{20,20,20},
				{30,30,30},
				{40,40,40},
				{50,50,50}
		};
		
		int korTotal = 0, engTotal = 0, mathTotal = 0;
		
		System.out.println("번호  국어  영어  수학  총점  평균");
		System.out.println("==========================");
		
		for(int i=0; i<score.length; i++) {
			int sum =0;
			float avg = 0.0f;
			
			korTotal += score[i][0];
			engTotal += score[i][1];
			mathTotal += score[i][2];
			System.out.printf("%3d", i+1);
			
			for(int j=0; j<score[i].length; j++) {
				sum += score[i][j];
				System.out.printf("%5d", score[i][j]);
			}
			
			avg = sum/(float)score[i].length;
			System.out.printf("%5d %5.1f%n", sum, avg);
		}
		
		System.out.println("===========================");
		System.out.printf("총점: 3%d %4d %4d%n", korTotal,engTotal, mathTotal);
		
	}

}
//결과
번호  국어  영어  수학  총점  평균
==========================
  1  100  100  100  300 100.0
  2   20   20   20   60  20.0
  3   30   30   30   90  30.0
  4   40   40   40  120  40.0
  5   50   50   50  150  50.0
===========================
총점: 3240  240  240

가변 배열

각기 다른 길이의 배열을 생성함으로써 고정된 형태가 아닌 보다 유동적인 가변 배열을 구성 할 수 있다.

'5x3'길이의 2차원 배열 score를 생성하는 코드가 있을 경우,

int[][] score = new int[5][3];

다음과 같다.

int[][] score = new int [5][];
score[0] = new int[3];
score[1] = new int[3];
score[2] = new int[3];
score[3] = new int[3];
score[4] = new int[3];

아래의 코드와 같이 생성과 초기화를 동시에 할 수 있다.

int[][] score = {
									{100,100,100,100},
									{20,20,20},
									{30,30},
									{40,40},
									{50,50,50}	
};

다차원 배열의 활용

좌표에 X표 구하기

package Array;

import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

public class MultiArrEx1 {

	public static void main(String[] args) {
		final int SIZE = 10;
		int x=0, y=0;
		
		char[][] board = new char [SIZE][SIZE];
		byte[][] shipBoard = {
			   //1,2,3,4,5,6,7,8,9
				{0,0,0,0,0,0,1,0,0},
				{1,1,1,1,0,0,1,0,0},
				{0,0,0,0,0,0,1,0,0},
				{0,0,0,0,0,0,1,0,0},
				{0,0,0,0,0,0,0,0,0},
				{1,1,0,1,0,0,0,0,0},
				{0,0,0,1,0,0,0,0,0},
				{0,0,0,1,0,0,0,0,0},
				{0,0,0,0,0,1,1,1,0}
		};
		
		for(int i=1; i<SIZE; i++)
			board[0][i] = board[i][0] = (char)(i+'0');
		
		Scanner scanner = new Scanner(System.in);
		
		while(true) {
			System.out.printf("좌표를 입력하세요 (종료 00) : ");
			String input = scanner.nextLine();
			
			if(input.length()==2) {
				x = input.charAt(0) - '0'; //문자를 숫자로 변환
				y = input.charAt(1) - '0';
				
				if(x==0 && y==0)
					break;
			}
			
			if(input.length() != 2 || x<=0 || x>=SIZE || y<=0 || y>=SIZE) {
				System.out.println("잘못된 입력입니다. 다시 입력해주세요.");
				continue;
			}
			
			board[x][y] = shipBoard[x-1][y-1]==1 ? '0' : 'x';
			
			for(int i=0; i<SIZE; i++) {
				System.out.println(board[i]);
			}
			System.out.println();
		}
		
	}

}

빙고

package Array;

import java.util.Scanner;

public class MultiArrEx2 {

	public static void main(String[] args) {
		final int SIZE = 5;
		int x = 0, y = 0, num = 0;
		
		int[][] bingo = new int [SIZE][SIZE];
		Scanner scanner = new Scanner(System.in);
		
		// 배열의 모든 요소를 1부터 SIZE*SIZE까지의 숫자로 초기화
		for(int i=0; i<SIZE; i++)
			for(int j=0; j<SIZE; j++)
				bingo[i][j] = i+SIZE +j+1;
		
		// 배열에 저장된 값을 뒤 섞는다. (shuffle)
		for(int i=0; i<SIZE; i++) {
			for(int j=0; j<SIZE; j++) {
				x=(int)(Math.random() * SIZE);
				y=(int)(Math.random() * SIZE);
				
				//bingo[i][j]와 임의로 선택된 값 (bingo[x][y])을 바꾼다.
				int tmp = bingo[i][j];
				bingo[i][j] = bingo[x][y];
				bingo[x][y] = tmp;
			}
		}
		do {
			for(int i =0; i<SIZE; i++) {
				for(int j=0; j<SIZE; j++)
					System.out.printf("%2d ", bingo[i][j]);
				System.out.println();
			}
			System.out.println();
			
			System.out.printf("1~%d의 숫자를 입력하세요. (종료:0) : ", SIZE * SIZE);
			String tmp = scanner.nextLine();
			num = Integer.parseInt(tmp);
			
			outer:
				for(int i =0; i<SIZE; i++) {
					for(int j=0; j<SIZE; j++) {
						if(bingo[i][j]==num) {
							bingo[i][j] = 0;
							break outer;
						}
					}
				}
		}while(num!=0);
		
	}

}

행렬의 곱셈

package Array;

public class MultiArrEx3 {

	public static void main(String[] args) {
		int[][] m1 = {
				{1,2,3},
				{4,5,6}
		};
		
		int[][] m2 = {
				{1,2},
				{3,4},
				{5,6}
		};
		
		final int ROW = m1.length;
		final int COL = m2[0].length;
		final int M2_ROW = m2.length;
		
		int[][] m3 = new int[ROW][COL];
		
		//행렬곱 m1 x m2의 결과를 m3에 저장
		for(int i=0; i<ROW; i++)
			for(int j=0; j<COL; j++)
				for(int k=0; k<M2_ROW; k++)
					m3[i][j] += m1[i][k] * m2[k][j];
		
		//행렬 m3를 출력
		for(int i=0; i<ROW; i++) {
			for(int j=0; j<ROW; j++) {
				System.out.printf("%3d ", m3[i][j]);
			}
			System.out.println();
		}
		
	}

}

단어 맞추기

package Array;

import java.util.Scanner;

public class MultiArrEx4 {

	public static void main(String[] args) {
		String[][] words = {
				{"chair", "의자"},
				{"computer", "컴퓨터"},
				{"integer", "정수"}
		};
		
		Scanner scanner = new Scanner(System.in);
		
		for(int i=0; i<words.length; i++) {
			System.out.printf("Q%d. %s의 뜻은?", i+1, words[i][0]);
			
			String tmp = scanner.nextLine();
			
			if(tmp.equals(words[i][1])) {
				System.out.printf("정답입니다. %n%n");
			}else {
				System.out.printf("틀렸습니다. 정답은 %s입니다. %n%n", words[i][1]);
			}
		}	
	}
}

 

출처 : JAVA의 정석 - (남궁성지음)