알고리즘 공부/프로그래머스
프로그래머스 코딩테스트 연습 - 연습문제 - 행렬의 덧셈
HRuler
2020. 10. 7. 18:22
1. 문제
문제 설명
행렬의 덧셈은 행과 열의 크기가 같은 두 행렬의 같은 행, 같은 열의 값을 서로 더한 결과가 됩니다. 2개의 행렬 arr1과 arr2를 입력받아, 행렬 덧셈의 결과를 반환하는 함수, solution을 완성해주세요. 제한 조건
|
2. 나의 풀이
class Solution {
public int[][] solution(int[][] arr1, int[][] arr2) {
int[][] answer = new int [arr1.length][arr1[0].length];
for(int i = 0; i < arr1.length; i = i + 1) {
for(int j = 0; j < arr1[i].length; j = j + 1) {
answer[i][j] = arr1[i][j] + arr2[i][j];
}
}
return answer;
}
}
3. 다른 사람 풀이
class SumMatrix {
int[][] sumMatrix(int[][] A, int[][] B) {
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];
}
}
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("틀렸습니다. 수정하는게 좋겠어요");
}
}
}