[알고리즘] 프로그래머스 - 모의고사

do_large·2020년 10월 17일
0

알고리즘

목록 보기
11/50
post-thumbnail

문제설명
1번 문제부터 마지막 문제까지의 정답이 순서대로 들은 배열 answers가 주어졌을 때, 가장 많은 문제를 맞힌 사람이 누구인지 배열에 담아 return 하도록 solution 함수를 작성해주세요.

제한조건
시험은 최대 10,000 문제로 구성되어있습니다.
문제의 정답은 1, 2, 3, 4, 5중 하나입니다.
가장 높은 점수를 받은 사람이 여럿일 경우, return하는 값을 오름차순 정렬해주세요.

풀이방법
1. countCorrect라는 함수를 만들어 1,2,3학생의 점수를 구한다.
2. max변수에 1,2,3 학생의 점수중 최고점을 넣는다
3. 최고점과 동일한 점수를 받은 학생을 smart배열에 넣은 후 return 한다.

function solution(answers) {
    let smart=[];
    const first =  [1,2,3,4,5];
    const second = [2,1,2,3,2,4,2,5];
    const third =  [3,3,1,1,2,2,4,4,5,5];
    
    const aResult = countCorrect(first);
    const bResult = countCorrect(second);
    const cResult = countCorrect(third);

    const max = Math.max(aResult, bResult,cResult)
    
    if(max===aResult) smart.push(1)
    if(max===bResult) smart.push(2)
    if(max===cResult) smart.push(3)


    function countCorrect(arr){
        let count=0;
        for(let i = 0; i < answers.length; i++){
            if(answers[i] === arr[i % (arr.length)]){
               count++;
            }
       }
       return count; 
        
    }
    
    return smart;
}

0개의 댓글