[JS] 프로그래머스 코딩테스트 - 모의고사

권이온·2025년 8월 17일

📚 문제

모의고사

📣 풀이

  • 시도한 풀이
    function solution(answers) {
        let answer = [];
        let max = 0;
        let score = [0, 0, 0];
        
        for (let i = 0; i < answers.length; i++) {
            if ((i % 5 !== 4) && (answers[i] === (i + 1) % 5)) {
                score[0] += 1;
            }
            if (i % 5 === 4 && answers[i] === 5) {
                score[0] += 1;
            }
            if (answers[i] === 2 && i % 2 === 0) {
                score[1] += 1;
            }
            if (answers[i] === 1 && i % 8 === 1) {
                score[1] += 1;
            }
            if (answers[i] === 3 && i % 8 === 3) {
                score[1] += 1;
            }
            if (answers[i] === 4 && i % 8 === 5) {
                score[1] += 1;
            }
            if (answers[i] === 5 && i % 8 === 7) {
                score[1] += 1;
            }
            if (answers[i] === 3 && ((i % 10 === 0) || (i % 10 === 1))) {
                score[2] += 1;
            }
            if (answers[i] === 1 && ((i % 10 === 2) || (i % 10 === 3))) {
                score[2] += 1;
            }
            if (answers[i] === 2 && ((i % 10 === 4) || (i % 10 === 5))) {
                score[2] += 1;
            }
            if (answers[i] === 4 && ((i % 10 === 6) || (i % 10 === 7))) {
                score[2] += 1;
            }
            if (answers[i] === 5 && ((i % 10 === 8) || (i % 10 === 9))) {
                score[2] += 1;
            }
        }
        
        max = Math.max(...score);
        
        for (let j = 0; j < score.length; j++) {
            if (score[j] === max) answer.push(j + 1);
        }
        
        return answer;
    }

💫코드 리뷰 & 반성

[어려웠던 점]
완전 탐색이다보니 경우 찾아서 넣어줘야 했었다.
사실 제일 좋은 건 entries()를 사용하는 것.

Math.max()에 배열을 넣을 때는 Spread 연산자 써야하는 거 깜빡했었다.

[새롭게 알게된 점]
배열의 entries() 메서드는 배열 내 데이터를 인덱스와 값으로 묶어서
순회할 수 잇는 Iterator 객체를 반환한다.

JavaScript의 array.entries() 메소드는 배열의 각 인덱스와 값으로 구성된 
키-값 쌍을 포함하는 새로운 Array Iterator 객체를 반환합니다.


ES6에서 Spread 연산자를 통해 Iterator 객체를 분리해낼 수 있다.

참고

코딩 테스트 합격자 되기 자바스크립트 - 이선협, 박경록 저

profile
인생은 아름다워

0개의 댓글