https://school.programmers.co.kr/learn/courses/30/lessons/120842?language=java
// 오답
class Solution {
public int[][] solution(int[] num_list, int n) {
int length = num_list.length();
int m = length / n;
int[][] answer = new int[n][m];
for (int i=0; i<n; i++) {
for (int j=0; i<j; j++) {
int count = 0;
count++;
answer[][] = num_list[count];
}
}
return answer;
}
}
1차원 배열을 2차원 배열로 새로 옮기는 것이 많이 어려웠다.
정답을 맞추지는 못했다.
class Solution {
public int[][] solution(int[] num_list, int n) {
int numRows = num_list.length / n;
int numCols = n;
int[][] answer = new int[numRows][numCols];
int idx = 0;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
answer[i][j] = num_list[idx];
idx++;
// 또는 answer[i][j] = num_list[idx++];
}
}
return answer;
}
}
1) Array의 길이를 구하는 length 메소드는 괄호가 필요없다.
단, 문자열(String)에 length()는 괄호를 붙여야만한다.
2) 반복문 내에서 변수를 선언하면 해당 변수는 반복문의 실행마다 새로 생성되고 초기화된다. (중요)
// 변수를 반복문 안에서 선언
for (int i=0; i<n; i++) {
for (int j=0; i<j; j++) {
int count = 0;
count++;
answer[][] = num_list[count];
}
}
---------------------
// 변수를 반복문 밖에서 선언
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// count 변수를 활용하여 num_list의 값을 2차원 배열에 할당
answer[i][j] = num_list[count++];
}
}
만약 반복문의 실행 횟수를 변수에 담고싶다면, 무조건 변수를 반복문 바깥에서 선언해야 한다.
3) 반복문의 두번째 부분을 신경쓰자!!!!!!!!!!