이번 문제에 대한 자세한 사항은 다음 링크를 참조하길 바랍니다.
이번 문제의 경우 처음에는 answers의 길이만큼만 객체 요소 내 배열을 탐색하는 식으로 풀었더니 정답은 잘 출력되나 자꾸 테스트 케이스에서 오류가 났다. 이유인 즉, answers의 길이가 객체 요소 내 배열의 길이보다 길 경우 undefined가 뜨기 때문에 'i % 객체 요소 내 배열의 길이'로 탐색용 인덱스를 잡아줘야 하는 문제였다. 이렇게 해도 되는 이유는 수포자가 문제를 찍는 방식은 일정한 길이의 패턴으로 반복되기 때문이다. 이 점을 해결하니 수월하게 풀렸다.
우선 내가 작성한 해답의 경우 answers의 길이만큼 for문을 돌면서 supojas를 이중 for문으로 탐색하여 answers의 값과 supoja.arr의 값들을 비교해 값이 같을 경우 supoja.cnt를 1씩 증가시킨다. for문을 마치고 나면 Math.max() 메서드를 사용해 가장 큰 값을 골라내고 supojas 배열 내 요소 중 가장 큰 값과 일치하는 cnt값을 가진 수포자들만 배열에 담아 반환한다. filter() 메서드를 사용한 버전은 cnt값을 증가시키는 대신 answers의 값과 일치하는 supoja.arr의 요소로 구성된 배열의 길이를 supoja.cnt에 할당한다.
Solutions
Solution 1.
function solution(answers) { const supojas = [ { supoja: 1, cnt: 0, arr: [1, 2, 3, 4, 5] }, { supoja: 2, cnt: 0, arr: [2, 1, 2, 3, 2, 4, 2, 5] }, { supoja: 3, cnt: 0, arr: [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] }, ]; /* My Solution */ for (let i = 0; i < answers.length; i++) { for (const supoja of supojas) { if (answers[i] === supoja.arr[i % supoja.arr.length]) supoja.cnt++; } } /* Filter Ver. */ // for (const supoja of supojas) { // supoja.cnt = answers.filter( // (val, i) => val === supoja.arr[i % supoja.arr.length] // ).length; // } const maxAns = Math.max(supojas[0].cnt, supojas[1].cnt, supojas[2].cnt); return supojas.filter((obj) => obj.cnt === maxAns).map((val) => val.supoja); }
함께 보기
Math.max() - JavaScript | MDN
The Math.max() function returns the largest of the zero or more numbers given as input parameters, or NaN if any parameter isn't a number and can't be converted into one.
developer.mozilla.org
Function.prototype.apply() - JavaScript | MDN
The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).
developer.mozilla.org
'👩💻 Programming > Coding Test 문제 풀이' 카테고리의 다른 글
[Programmers] level 1: 폰켓몬 by JavaScript (0) | 2022.07.06 |
---|---|
[Programmers] level 1: 체육복 by JavaScript (0) | 2022.07.06 |
[Programmers] level 1: K번째 수 by JavaScript (0) | 2022.07.04 |
[Programmers] level 1: 완주하지 못한 선수 by JavaScript (0) | 2022.07.04 |
[Programmers] level 1: 소수 만들기 by JavaScript (0) | 2022.07.02 |
댓글