[Java] 프로그래머스 (로또의 최고 순위와 최저 순위) Dev-Matching 1
Algorithm/Programmers

[Java] 프로그래머스 (로또의 최고 순위와 최저 순위) Dev-Matching 1

Problem : https://programmers.co.kr/learn/courses/30/lessons/77484

 

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

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

programmers.co.kr

 

Approach

먼저 주어진 입력에서 0의 개수를 센다.

최고 순위0이 모두 당첨번호와 같다는 것을 가정하여 계산하고, 최저 순위0이 모두 당첨번호와 다르다는 것을 가정하여 계산한다.

그리고 난 뒤, 일치하는 번호의 개수를 가지고 등수를 계산하여 반환하면 되는 간단한 문제이다.

 

Code

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

public class HighestAndLowestRankingInLotto {
    public int[] solution(int[] lottos, int[] win_nums) {
        int same = 0;
        int zero = 0;
        for (int i = 0; i < 6; i++) {
            if (lottos[i] == 0) {
                zero++;
                continue;
            }

            for (int j = 0; j < 6; j++) {
                if (lottos[i] == win_nums[j]) {
                    same++;
                    break;
                }
            }
        }

        int highRating = same + zero >= 2 ? 7 - (same + zero) : 6;
        int lowRating = same >= 2 ? 7 - same : 6;
        return new int[]{highRating, lowRating};
    }

    @Test
    void test() {
        assertArrayEquals(new int[]{3, 5}, solution(new int[]{44, 1, 0, 0, 31, 25}, new int[]{31, 10, 45, 1, 6, 19}));
        assertArrayEquals(new int[]{1, 6}, solution(new int[]{0, 0, 0, 0, 0, 0}, new int[]{38, 19, 20, 40, 15, 25}));
        assertArrayEquals(new int[]{1, 1}, solution(new int[]{45, 4, 35, 20, 3, 9}, new int[]{20, 9, 3, 45, 4, 35}));
    }
}