문제 풀이/프로그래머스 알고리즘

행렬의 덧셈 // 이중for문, 스트림

열심히 해 2024. 10. 7. 20:57

https://school.programmers.co.kr/learn/courses/30/lessons/12950

 

 

1. 

class Solution {
    public int[][] solution(int[][] arr1, int[][] arr2) {

        int rows = arr1.length;
        int cols = arr1[0].length;

        int[][] answer = new int[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j<cols; j++ ) {
                answer[i][j] = arr1[i][j] + arr2[i][j];
            }
        }

        return answer;
    }
}

 

2. 

import java.util.stream.IntStream;

class Solution {
    public int[][] solution(int[][] arr1, int[][] arr2) {
        int rows = arr1.length;
        int cols = arr1[0].length;

        // 각 행에 대해 처리
        return IntStream.range(0, rows)
                .mapToObj(i ->
                        // 각 열에 대해 처리하여 두 행렬의 값을 더함
                        IntStream.range(0, cols)
                                .map(j -> arr1[i][j] + arr2[i][j])
                                .toArray() // 한 행의 결과를 배열로 변환
                )
                .toArray(int[][]::new); // 모든 행을 2차원 배열로 변환
    }
}