본문 바로가기

1일1알고리즘

모의고사, 배열비교와 filter() | 프로그래머스 코딩테스트 [자바스크립트]

 

코딩테스트 연습 - 모의고사

수포자는 수학을 포기한 사람의 준말입니다. 수포자 삼인방은 모의고사에 수학 문제를 전부 찍으려 합니다. 수포자는 1번 문제부터 마지막 문제까지 다음과 같이 찍습니다. 1번 수포자가 찍는 ��

programmers.co.kr

수포자1, 2, 3은 각각 일정한 규칙에 따라 배열을 찍어냄. 수포자들의 배열과 주어진 배열의 요소를 비교해서 요소가 가장 많이 겹치는 배열을 가려내는 문제.

 

function solution(answers) {
    let result = [];
    
    const supo1Score = compare(answers, supo1(answers));
    const supo2Score = compare(answers, supo2(answers));
    const supo3Score = compare(answers, supo3(answers));
    
    if (supo1Score > supo2Score && supo1Score > supo3Score) {
        result.push(1);
    } else if (supo2Score > supo1Score && supo2Score > supo3Score) {
        result.push(2);
    } else if (supo3Score > supo1Score && supo3Score > supo2Score) {
        result.push(3);
    } else if (supo1Score === supo2Score && supo1Score > supo3Score) {
        result.push(1, 2);
    } else if (supo1Score === supo3Score && supo1Score > supo2Score) {
        result.push(1, 3);
    } else if (supo2Score === supo3Score && supo2Score > supo1Score) {
        result.push(2, 3);
    } else {
        result.push(1, 2, 3);
    }
    
    return result;
}

function supo1(answers) {
    let supo1 = [];
    
    for (let i = 1; i < answers.length + 1; i++) {
        if (i % 5 !== 0) {
            supo1.push(i % 5);
        } else {
            supo1.push(5);
        }        
    }
    
    return supo1;
}

function supo2(answers) {
    let supo2 = [];
    
    for (let i = 1; i < answers.length + 1; i++) {
        if (i % 2 !== 0) {
            supo2.push(2);
        } else if (i % 8 === 2) {
            supo2.push(1);
        } else if (i % 8 === 4) {
            supo2.push(3);
        } else if (i % 8 === 6) {
            supo2.push(4);
        } else if (i % 8 === 0) {
            supo2.push(5);
        }
    }
    
    return supo2;
}

function supo3(answers) {
    let supo3 = [];
    
    for (let i = 1; i < answers.length + 1; i++) {
        if (i % 10 === 1 || i % 10 === 2) {
            supo3.push(3);
        } else if (i % 10 === 3 || i % 10 === 4) {
            supo3.push(1);
        } else if (i % 10 === 5 || i % 10 === 6) {
            supo3.push(2);
        } else if (i % 10 === 7 || i % 10 === 8) {
            supo3.push(4);
        } else {
            supo3.push(5);
        }
    }
    
    return supo3;
}

function compare(answers, supo) {
    let same = 0;
    
    for (let i = 0; i < answers.length; i++) {
        if (answers[i] === supo[i]) {
            same++;
        }
    }
    
    return same;
}

 

채점 과정에서 효율성은 따지지 않아서 무난하게 통과했으나 너무 무식하게 코드를 짠듯.

 

그래서 다른 사람들의 답변을 참고해서 공부함.

function solution(answers) {
    const answer = [];
    
    const supo1 = [1, 2, 3, 4, 5];
    const supo2 = [2, 1, 2, 3, 2, 4, 2, 5]
    const supo3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5];

    const supo1Correct = answers.filter((eachAnswer, index) => eachAnswer === supo1[index % supo1.length]).length;
    const supo2Correct = answers.filter((eachAnswer, index) => eachAnswer === supo2[index % supo2.length]).length;
    const supo3Correct = answers.filter((eachAnswer, index) => eachAnswer === supo3[index % supo3.length]).length;
    const max = Math.max(supo1Correct, supo2Correct, supo3Correct);

    if (supo1Correct === max) { answer.push(1) };
    if (supo2Correct === max) { answer.push(2) };
    if (supo3Correct === max) { answer.push(3) };

    return answer;
}

구동 시간 훨씬 짧음.

 

filter().

 

Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

developer.mozilla.org

let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])

element는 필수 요소, 나머지는 선택적. 위 답변에선 index까지 씀. forEach처럼 callback을 이용함.

 

그리고 또 한 가지 기억할 건 멤버접근 연산자(.)가 나머지 연산자(%)보다 우선순위가 높다는 점.