저장을 습관화
프로그래머스 LV.0 특별한 이차원 배열 1 본문
프로그래머스 LV.0 특별한 이차원 배열 1
https://school.programmers.co.kr/learn/courses/30/lessons/181833
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
1. 문제 명
특별한 이차원 배열 1
2. 문제 설명
정수 n이 매개변수로 주어질 때, 다음과 같은 n × n 크기의 이차원 배열 arr를 return 하는 solution 함수를 작성해 주세요.
- arr[i][j] (0 ≤ i, j < n)의 값은 i = j라면 1, 아니라면 0입니다.
3. 제한 사항
- 1 ≤ n ≤ 100
4. 예시
n | result |
3 | [[1, 0, 0], [0, 1, 0], [0, 0, 1]] |
6 | [[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]] |
1 | [[1]] |
5. 기본 제공 코드
function solution(n) {
var answer = [[]];
return answer;
}
6. 제출한 내 답
const solution = (n) => {
let a = [[]];
if (n === 1) {
return [[1]];
} else {
for (i = 0; i < n; i++) {
a[i] = [];
for (j = 0; j < n; j++) {
i === j ? a[i].push(1) : a[i].push(0);
}
}
}
return a;
};
6-2. VSC에 작성한 내용
const solution = (n) => {
let a = [[]];
if (n === 1) {
return [[1]];
} else {
for (i = 0; i < n; i++) {
a[i] = [];
for (j = 0; j < n; j++) {
i === j ? a[i].push(1) : a[i].push(0);
}
}
}
return a;
};
// 테스트
console.log(solution(3));
console.log(solution(6));
console.log(solution(1));
7. 특이사항
i 반복문 안에 a[i] = [] 선언이 없었어서
계속 TypeError: Cannot read properties of undefined (reading 'push') 에러가 났었다
맨 처음 a = [[]] 배열 안 배열이 있다고 선언해주는거로는 안되는구나
8. 다른 사람이 작성한 답
8-1. Arrary
function solution(n) {
const answer = Array.from(Array(n), () => Array(n).fill(0));
for (let i = 0; i < n; i++) {
answer[i][i] = 1;
}
return answer;
}
8-2. Array
function solution(n) {
const answer = [];
for(let i=0; i<n; i++) {
const row = new Array(n).fill(0);
{
row[i] = 1;
}
answer.push(row);
}
return answer;
}
'코딩 테스트 > 프로그래머스 - 자바스크립트' 카테고리의 다른 글
프로그래머스 LV.0 x 사이의 개수 (0) | 2023.09.20 |
---|---|
프로그래머스 LV.0 가까운 1 찾기 (0) | 2023.09.20 |
프로그래머스 LV.0 주사위의 개수 (0) | 2023.09.20 |
프로그래머스 LV.0 콜라츠 수열 만들기 (0) | 2023.09.20 |
프로그래머스 LV.0 외계행성의 나이 (0) | 2023.09.20 |