프로그래머스 실패율 JAVA

sundays·2022년 9월 19일
0

문제

실패율

풀이

하위의 코드는 조금 틀렸다

	/**
     * 실패율이 높은 스테이지부터 내림차순으로 스테이지의 번호가 담겨있는 배열
     * 
     * @param N      전체 스테이지의 개수
     * @param stages 게임을 이용하는 사용자가 현재 멈춰있는 스테이지의 번호가 담긴 배열
     * @return
     */
    public static int[] solution(int N, int[] stages) {
        ArrayList<Game> game = new ArrayList<>();
        int[] answer = new int[N];
        int[] failureCnt = new int[N + 1]; // 아직 클리어하지 못한 플레이어의 수
        int[] reached = new int[N + 1]; // 스테이지에 도달한 플레이어 수
        for (int i = 0; i < stages.length; i++) {
            failureCnt[stages[i] - 1]++;
            for (int j = 0; j < stages[i]; j++) {
                reached[j]++;
            }
        }

        for (int i = 0; i < N; i++) {
            game.add(new Game(i, (double) failureCnt[i] / (double) reached[i]));
        }

        Collections.sort(game);

        for (int i = 0; i < game.size(); i++) {
            answer[i] = game.get(i).stage + 1;
        }
        return answer;
    }

    static class Game implements Comparable<Game> {
        int stage;
        double failurePercent;

        Game(int stage, double failurePercent) {
            this.stage = stage;
            this.failurePercent = failurePercent;
        }

        @Override
        public int compareTo(Game o) {
            if (this.failurePercent - o.failurePercent > 0) {
                return -1;
            } else if (this.failurePercent - o.failurePercent == 0) {
                return 0;
            } else {
                return 1;
            }
        }
    }

틀린 이유는 정말 간단한데, 예외처리를 안했기 때문이다.
실패율을 계산하는 부분에서 분모가 0이 되는 경우 나눗셈을 할때 Nan 이 입력되는 것이 문제였다.

		for (int i = 0; i < N; i++) {
            if (reached[i] == 0) {
                game.add(new Game(i, 0));
            } else {
                game.add(new Game(i, (double) failureCnt[i] / (double) reached[i]));
            }
        }

이코드도 더 짧게 수정 가능 할 것 같은데 나중에 한꺼번에 보는 시간을 가져야 겠다

전체 코드

전체 코드

profile
develop life

0개의 댓글