본문 바로가기

Algorithms/Programmers

Level 1 - 행렬의 덧셈

행렬의 덧셈은 행과 열의 크기가 같은 두 행렬의 같은 행, 같은 열의 값을 서로 더한 결과가 됩니다. 2개의 행렬을 입력받는 sumMatrix 함수를 완성하여 행렬 덧셈의 결과를 반환해 주세요.

예를 들어 2x2 행렬인 A = ((1, 2), (2, 3)), B = ((3, 4), (5, 6)) 가 주어지면, 같은 2x2 행렬인 ((4, 6), (7, 9))를 반환하면 됩니다.(어떠한 행렬에도 대응하는 함수를 완성해주세요.)


풀이

class SumMatrix {

int[][] sumMatrix(int[][] A, int[][] B) {

int[][] answer = new int[A.length][A[0].length];

        for (int i = 0; i < A.length; i++) {

            for (int j = 0; j < A[i].length; j++) {

                answer[i][j] = A[i][j] + B[i][j];

            }

        }

return answer;

}


// 아래는 테스트로 출력해 보기 위한 코드입니다.

public static void main(String[] args) {

SumMatrix c = new SumMatrix();

int[][] A = { { 1, 2 }, { 2, 3 } };

int[][] B = { { 3, 4 }, { 5, 6 } };

int[][] answer = c.sumMatrix(A, B);

if (answer[0][0] == 4 && answer[0][1] == 6 && 

answer[1][0] == 7 && answer[1][1] == 9) {

System.out.println("맞았습니다. 제출을 눌러 보세요");

} else {

System.out.println("틀렸습니다. 수정하는게 좋겠어요");

}

}

}


다른 사람이 푼 코드를 보니 더 괜찮아보이는 것 찾음
int row = Math.max(A.length, B.length);
int col = Math.max(A[0].length, B[0].length);
//int[][] answer = {{0, 0}, {0, 0}};
int[][] answer = new int[row][col];
for(int i=0; i<row ; i++){
for(int j=0; j<col; j++){
answer[i][j] = A[i][j] + B[i][j];
}
}

row, col에 A배열이나 B배열중에서 최대값을 지정해서 answer를 구성하면 더 깔끔하게 마무릳 되는 거 같다

'Algorithms > Programmers' 카테고리의 다른 글

Level 1 - 서울에서김서방찾기  (0) 2018.02.13
Level 1 - 스트링을 숫자로 바꾸기  (0) 2018.02.13
Level 1- 짝수와 홀수  (0) 2018.02.13
Level 1 - 삼각형출력하기  (0) 2018.02.13
Level 1 - 약수의 합  (0) 2018.02.09