영운's 블로그

[프로그래머스 Lv1] 로또의 최고 순위와 최저 순위(Java) 본문

백준 , 프로그래머스 풀이/프로그래머스 Lv1 (Java)

[프로그래머스 Lv1] 로또의 최고 순위와 최저 순위(Java)

오영운(you88) 2022. 3. 29. 17:20

https://programmers.co.kr/learn/courses/30/lessons/77484?language=java 

 

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

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

programmers.co.kr

0은 지워진 번호라고 가정하고 최대 몇등 최소 몇등인지 찾아내는 문제다.

 

핵심은 lottos[]에 맞는 숫자가 1개 이하일 때 어떻게 처리할가 이다.

숫자가 2개 이상 맞는 경우 최소당첨 등수: 7 - (맞춘 숫자 개수)

                                   최대당첨 등수: 7 - (맞춘 숫자 개수 + 0 개수)

가 성립하지만 숫자가 1개 이하인 경우 성립하지 않기 때문이다. (1개이하의 숫자를 맞춘 경우 당첨금이 없다.)

 

Math클래스의 min() 함수를 이용하여 이를 해결하였다.

7 - xx가 6보다 작은 경우 6이 되도록 만들었다.

 

 

import java.lang.Math;

public class Solution {

    public int[] solution(int[] lottos, int[] win_nums) {

        int erased_cnt = 0;
        int winning_cnt = 0;
        int j = 0;

        for (int lot_num : lottos) {
            if (lot_num == 0)
                erased_cnt++;
            else {
                for (int win_num : win_nums) {
                    if (lot_num == win_num)
                        winning_cnt++;
                }
            }
        }

        int min = Math.min(7 - winning_cnt, 6);
        int max = Math.min(7 - (winning_cnt + erased_cnt), 6);

        return new int[]{max, min};
    }

    public static void main(String[] args) {
        int[] lottos = {44, 1, 0, 0, 31, 25};
        int[] win_nums = {31, 10, 45, 1, 6, 19};

        Solution sol = new Solution();

        int[] answer = sol.solution(lottos, win_nums);
        System.out.printf("[%d, %d]",answer[0],answer[1]);
    }

}

결과값

Comments