본문 바로가기
코딩테스트(알고리즘)

[프로그래머스] 로또의 최고 순위와 최저 순위_Javascript

by Cafe Mocha 2022. 4. 27.

코딩 테스트 연습 - 로또의 최고 순위와 최저 순위 | 프로그래머스 (programmers.co.kr)

 

코딩테스트 연습 - 로또의 최고 순위와 최저 순위

로또 6/45(이하 '로또'로 표기)는 1부터 45까지의 숫자 중 6개를 찍어서 맞히는 대표적인 복권입니다. 아래는 로또의 순위를 정하는 방식입니다. 1 순위 당첨 내용 1 6개 번호가 모두 일치 2 5개 번호

programmers.co.kr

 

나의 풀이

function solution(lottos, win_nums) {
    var answer = [];
    
    let numZero = lottos.filter(val=>val === 0).length;
    
    let intersection = lottos.filter(val=>win_nums.includes(val));
    let difference = lottos.filter(val=>!win_nums.includes(val));
    
    let ans_min = 7-intersection.length;
    let ans_max = ans_min-numZero;

    console.log(intersection);    
    console.log(difference);
    console.log(ans_min);
    console.log(ans_max);
    
    
    if(ans_min <= 5){
        answer.push(ans_max);
        answer.push(ans_min);
    } else if(numZero===0 && ans_max === 7){
        answer.push(6);
        answer.push(6);
    } else {
        answer.push(ans_max);
        answer.push(6);
    }
    
    
    return answer;
}

 

다른 풀이

function solution(lottos, win_nums) {
    const answer = [];
    const min = lottos.filter(n => win_nums.includes(n)).length;
    const max = lottos.filter(n => n === 0).length + min;

    max > 1 ? answer.push(7 - max) : answer.push(6);
    min > 1 ? answer.push(7 - min) : answer.push(6);

    return answer;
}

 


정답은 맞췄지만 효율성 부분에서 많이 부족함을 느꼈다.

또한, 테스트 케이스도 처음 풀이에서는 한 가지를 고려하지 못했다.

 

조금 더 깔끔한 코드를 작성하고 조건을 꼼꼼히 챙기는 연습을 해야겠다.

 

filter, include를 활용한 문제.