코딩테스트 풀이/JAVA
[프로그래머스/Lv.0] 2차원으로 만들기
무지맘
2022. 10. 25. 13:42
1. Input
1) 정수 배열 num_list
2) 정수 n
2. Output
1) num_list를 2차원 배열로 바꾼 결과
2) Example에서 설명
3. Constraint
1) num_list의 길이는 n의 배수
2) 0 <= num_list의 길이 <= 150
3) 2 <= n < num_list의 길이
4. Example
Input: num_list={1,2,3,4,5,6,7,8}, n=2 -> Output: {{1,2},{3,4},{5,6},{7,8}}
설명: num_list의 길이가 8이고 n=2이므로 2*4배열로 변경. 이때 가로가 2이므로 배열의 열이 2, 세로가 4이므로 배열의 행이 4가 된다. 따라서 결과는 {{1,2},{3,4},{5,6},{7,8}}
- 비교: {{1,2,3,4},{5,6,7,8}}은 4*2배열이다.
5. Code
1) 첫 코드(2022/10/25)
int[][] answer = new int[num_list.length/n][n];
int index = 0;
for(int i=0 ; i<num_list.length/n ; i++){
for(int j=0 ; j<n ; j++){
answer[i][j] = num_list[index++];
}// for j
}// for i
return answer;
2) 간단하게 바꾼 코드(2022/10/25)
int[][] answer = new int[num_list.length/n][n];
for(int i=0 ; i<num_list.length ; i++)
answer[i/n][i%n] = num_list[i];
return answer;