。゚(*´□`)゚。

코딩의 즐거움과 도전, 그리고 일상의 소소한 순간들이 어우러진 블로그

ㅋㅌ

묘경이한테 물어보기

quarrrter 2023. 7. 3. 19:22

정수 배열 num_list와 정수 n이 매개변수로 주어집니다. num_list를 다음 설명과 같이 2차원 배열로 바꿔 return하도록 solution 함수를 완성해주세요.

num_list가 [1, 2, 3, 4, 5, 6, 7, 8] 로 길이가 8이고 n이 2이므로 num_list를 2 * 4 배열로 다음과 같이 변경합니다. 2차원으로 바꿀 때에는 num_list의 원소들을 앞에서부터 n개씩 나눠 2차원 배열로 변경합니다.

import java.util.*;

class Solution {
    public int[][] solution(int[] num_list, int n) {
        int rows =  num_list.length / n; // 행의 개수
        int[][] result = new int[rows][n]; // 결과 배열 초기화

        int index = 0; // num_list에서 원소를 가져오기 위한 인덱스 변수

        // num_list의 원소들을 2차원 배열로 옮깁니다.
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < n; j++) {
                if (index < num_list.length) {
                    result[i][j] = num_list[index++];
                } 
            }
        }

        return result;
    }
}