Lewis's Tech Keep

[프로그래머스] 복서 정렬하기 - JAVA 본문

Java/알고리즘

[프로그래머스] 복서 정렬하기 - JAVA

Lewis Seo 2021. 9. 13. 13:11

- 링크 : https://programmers.co.kr/learn/courses/30/lessons/85002?language=java

 

코딩테스트 연습 - 6주차_복서 정렬하기

복서 선수들의 몸무게 weights와, 복서 선수들의 전적을 나타내는 head2head가 매개변수로 주어집니다. 복서 선수들의 번호를 다음과 같은 순서로 정렬한 후 return 하도록 solution 함수를 완성해주세요

programmers.co.kr

 

- 풀이 

 - 문제에서 요구되는 조건을 충실하게 구현하면 되는 문제

 - 구현 마지막에 기준에 따라 정렬

 

더보기
import java.util.*;

class Solution {
    public int[] solution(int[] weights, String[] head2head) {
        int[] answer = new int[weights.length];
        List<Boxer> arr = new ArrayList<>();
        
        for (int i=0; i<weights.length; i++) {
            int weight = weights[i];
            String head = head2head[i];
            arr.add(new Boxer(i, weight, head, weights));
        }
        
        arr.sort(Comparator.comparing(Boxer::getWinRate)
                            .thenComparing(Boxer::getWinHeavyCount)
                            .thenComparing(Boxer::getWeight).reversed()
                            .thenComparing(Boxer::getIdx));
        
        for (int i=0; i<arr.size(); i++) {
            answer[i] = arr.get(i).getIdx() + 1;
        }
        
        return answer;
    }
}

class Boxer {
    int idx;
    int weight;
    String head;
    int[] weightsBase;
    double winRate;
    int winHeavyCount;
    
    Boxer(int idx, int weight, String head, int[] weightsBase) {
        this.idx = idx;
        this.weight = weight;
        this.head = head;
        this.weightsBase = weightsBase;
        getWinRate(head);
    }
    
    private void getWinRate(String head) {
        int count = 0;
        int noCount = 0;
        int len = head.length();
        for (int i=0; i<len; i++) {
            int vsWeight = this.weightsBase[i];
            char c = head.charAt(i);
            if (c == 'W') {
                count++;
                if (vsWeight > weight) {
                    winHeavyCount++;
                }
            }
            if (c == 'N') {
                noCount++;
            }
        }
        
        len -= noCount;
        
        this.winRate = len == 0 ? 0 : ((double) count / (double) len) * 100;
    }
    
    public int getIdx() {
        return idx;
    }
    
    public int getWeight() {
        return weight;
    }
    
    public double getWinRate() {
        return winRate;
    }
    
    public int getWinHeavyCount() {
        return winHeavyCount;
    }
    
    
}
Comments