프로그래머스/JAVA/등수 메기기

Seoung Young Oh·2022년 12월 26일
0

프로그래머스

목록 보기
91/105
post-thumbnail

문제설명

영어 점수와 수학 점수의 평균 점수를 기준으로 학생들의 등수를 매기려고 합니다. 영어 점수와 수학 점수를 담은 2차원 정수 배열 score가 주어질 때, 영어 점수와 수학 점수의 평균을 기준으로 매긴 등수를 담은 배열을 return하도록 solution 함수를 완성해주세요.

제한사항

  • 0 ≤ score[0], score[1] ≤ 100
  • 1 ≤ score의 길이 ≤ 10
  • score의 원소 길이는 2입니다.
  • score는 중복된 원소를 갖지 않습니다.

입출력 예

scoreresult
[[80, 70], [90, 50], [40, 70], [50, 80]][1, 2, 4, 3]
[[80, 70], [70, 80], [30, 50], [90, 100], [100, 90], [100, 100], [10, 30]][4, 4, 6, 2, 2, 1, 7]

입출력 예 설명

입출력 예 #1

  • 평균은 각각 75, 70, 55, 65 이므로 등수를 매겨 [1, 2, 4, 3]을 return합니다.

입출력 예 #2

  • 평균은 각각 75, 75, 40, 95, 95, 100, 20 이므로 [4, 4, 6, 2, 2, 1, 7] 을 return합니다.
    공동 2등이 두 명, 공동 4등이 2명 이므로 3등과 5등은 없습니다.

풀이

처음 작성한 코드는 테스트 케이스 2번이계속 실패하는 바람에 해결하지 못하고 
다른 코드를 참고 해서 해결했다.

scoreList를 선언하여 각 요소의 점수 합을 scoreList에 add한다.
평균이라고 해서 굳이 나눌필요 없이 총점으로 점수 순위를 매기는 것이 더 간편하다.

scoreList를 내림차순으로 정렬한다.
그럼 가장높은 점수가 맨 처음으로 오게된다.

answer배열을 선언하여,
scoreList에서 score[i][0] + score[i][1]의 인덱스를 indexOf로 리턴시키고, 
그 값에 1을 더해준 값을 answer요소로 순서대로 삽입한다.
indexOf는 맨 앞에 있는 인텍스 값을 리턴하기 때문에 자동으로 중복요소도 처리 된다.
import java.util.*;

class Solution {

	public int[] solution(int[][] score) {

		List<Integer>scoreList = new  ArrayList<>();
		
		for (int i = 0; i < score.length; i++) {
			scoreList.add(score[i][0] + score[i][1]);
		}
		scoreList.sort(Comparator.reverseOrder());
		
		int[] answer = new int[score.length];
		for (int i = 0; i < score.length; i++) {
			answer[i] = scoreList.indexOf(score[i][0] + score[i][1]) + 1;
		}

		return answer;
	}
}

미해결 코드

import java.util.*;

class Solution {

	public int[] solution(int[][] score) {

		int[] sumScore = new int[score.length];

		for (int i = 0; i < sumScore.length; i++) {
			sumScore[i] = (score[i][0] + score[i][1]);
		}

		int[] removeDuplication = Arrays.stream(sumScore).distinct().toArray();

		removeDuplication = Arrays.stream(sumScore).boxed().sorted(Collections.reverseOrder())
				.mapToInt(Integer::valueOf).toArray();
		
		Map<Integer, Integer> map = new HashMap<>();

		int order = 1;

		for (int i = 0; i < removeDuplication.length; i++) {

			for (int j = 0; j < sumScore.length; j++) {
				if (removeDuplication[i] == sumScore[j]) {
					if (!map.containsKey(sumScore[j])) {
						map.put(sumScore[j], order);
					}
				}
			}
			order++;
		}
		map.forEach((key, value) -> {
			System.out.println(key + " : " + value);
			for (int i = 0; i < sumScore.length; i++) {
				if(key==sumScore[i]) {
					sumScore[i]=value;
				}
				
			}
		});
	
		return sumScore;
	}
}	

참고

0개의 댓글