2차원으로 만들기

반즈·2023년 12월 20일

프로그래머스 입문

목록 보기
49/51

문제 설명

정수 배열 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차원 배열로 변경합니다.

입출력 예


자바

나의 풀이

class Solution {
    public int[][] solution(int[] num_list, int n) {
        int[][] answer = new int[num_list.length / n][n];
        int tmp = 0;
        for(int i = 0; i < num_list.length / n; i++){
            for(int j = 0; j < n; j++){
                answer[i][j] = num_list[tmp];
                tmp++;
            }
        }
        return answer;
    }
}

참고 풀이 (/n %n)

class Solution {
    public int[][] solution(int[] num_list, int n) {
        int[][] answer = {};

        int length = num_list.length;

        answer = new int[length/n][n];

        for(int i=0; i<length; i++){
            answer[i/n][i%n]=num_list[i];
        }

        return answer;
    }
}

자바스크립트

나의 풀이 (참고 풀이 참조함)

function solution(num_list, n) {
    var answer = [];
    
    for(let i = 0; i < num_list.length; i+=n){
        answer.push(num_list.slice(i, n + i));
    }
    return answer;
}

참고 풀이 1 (.splice())

function solution(num_list, n) {
    var answer = [];

    while(num_list.length) {
        answer.push(num_list.splice(0,n));
    }

    return answer;
}

참고 풀이 2 (.slice())

function solution(num_list, n) {
	var answer = [];
    for (let i = 0; i < num_list.length; i += n) {
    	answer.push(num_list.slice(i, i + n));
    }
	return answer;
}
profile
나를 채우다

0개의 댓글