-
[Programmers] JavaScript 알고리즘 | Lv.0 배열의 원소만큼 추가하기► JS Algorithm/Programmers 2024. 1. 5. 20:28반응형
🔒 문제 설명
아무 원소도 들어있지 않은 빈 배열 X가 있습니다. 양의 정수 배열 arr가 매개변수로 주어질 때, arr의 앞에서부터 차례대로 원소를 보면서 원소가 a라면 X의 맨 뒤에 a를 a번 추가하는 일을 반복한 뒤의 배열 X를 return 하는 solution 함수를 작성해 주세요.
🔒 제한사항
- 1 ≤ arr의 길이 ≤ 100
- 1 ≤ arr의 원소 ≤ 100
🔒 입출력 예
arr result [5, 1, 4] [5, 5, 5, 5, 5, 1, 4, 4, 4, 4] [6, 6] [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6] [1] [1]
🔒 입출력 예 설명
입출력 예 #1
- 예제 1번에 대해서 a와 X를 나타내보면 다음 표와 같습니다.
a X [] 5 [5, 5, 5, 5, 5] 1 [5, 5, 5, 5, 5, 1] 4 [5, 5, 5, 5, 5, 1, 4, 4, 4, 4] 따라서 [5, 5, 5, 5, 5, 1, 4, 4, 4, 4]를 return 합니다.
입출력 예 #2
- 예제 2번에 대해서 a와 X를 나타내보면 다음 표와 같습니다.
a X [] 6 [6, 6, 6, 6, 6, 6] 6 [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6] 따라서 [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]를 return 합니다.
입출력 예 #3
- 예제 2번에 대해서 a와 X를 나타내보면 다음 표와 같습니다.
a X [] 1 [1] 따라서 [1]을 return 합니다.
🔐 solution of mine
forEach()
push()
new Array()
Array.fill()
const solution = (arr) => { let answer = []; arr.forEach((v, i) => answer.push(...new Array(v).fill(v))); return console.log(answer); }; solution([5, 1, 4]); // expected output: [5, 5, 5, 5, 5, 1, 4, 4, 4, 4] solution([6, 6]); // expected output: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6] solution([1]); // expected output: [1]
🔐 solution of others
reduce()
new Array()
Array.fill()
const solution = (arr) => arr.reduce((acc, cur) => [...acc, ...new Array(cur).fill(cur)], []);
🔐 solution of others
reduce()
concat()
Array()
fill()
const solution = (arr) => console.log( arr.reduce((acc, cur) => acc.concat(Array(cur).fill(cur)), []) ); solution([5, 1, 4]); // expected output: [5, 5, 5, 5, 5, 1, 4, 4, 4, 4] solution([6, 6]); // expected output: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6] solution([1]); // expected output: [1]
🔐 solution of others
map()
Array()
fill()
flat()
const solution = (arr) => console.log(arr.map((v) => Array(v).fill(v)).flat()); solution([5, 1, 4]); // expected output: [5, 5, 5, 5, 5, 1, 4, 4, 4, 4] solution([6, 6]); // expected output: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6] solution([1]); // expected output: [1]
🔐 solution of others
flatMap()
Array()
fill()
const solution = (arr) => console.log(arr.flatMap((v) => Array(v).fill(v))); solution([5, 1, 4]); // expected output: [5, 5, 5, 5, 5, 1, 4, 4, 4, 4] solution([6, 6]); // expected output: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6] solution([1]); // expected output: [1]
반응형'► JS Algorithm > Programmers' 카테고리의 다른 글
[Programmers] JavaScript 알고리즘 | Lv.0 부분 문자열 이어 붙여 문자열 만들기 (0) 2024.01.05 [Programmers] JavaScript 알고리즘 | Lv.0 할 일 목록 (2) 2024.01.05 [Programmers] JavaScript 알고리즘 | Lv.0 주사위 게임 1 (0) 2024.01.05 [Programmers] JavaScript 알고리즘 | Lv.0 순서 바꾸기 (0) 2024.01.05 [Programmers] JavaScript 알고리즘 | Lv.0 암호 해독 (0) 2024.01.05