코딩테스트/Programmers
[Programmers] 입문) 등수 매기기
HONGGG
2023. 7. 24. 05:27
등수 매기기
문제 설명
영어 점수와 수학 점수의 평균 점수를 기준으로 학생들의 등수를 매기려고 합니다. 영어 점수와 수학 점수를 담은 2차원 정수 배열 score가 주어질 때, 영어 점수와 수학 점수의 평균을 기준으로 매긴 등수를 담은 배열을 return하도록 solution 함수를 완성해주세요.
제한사항
- 0 ≤ score[0], score[1] ≤ 100
- 1 ≤ score의 길이 ≤ 10
- score의 원소 길이는 2입니다.
- score는 중복된 원소를 갖지 않습니다.
입출력 예
score | result |
[[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] |
[[0, 20], [80, 100], [10, 10], [90, 90], [20, 0]] | [3, 1, 3, 1, 3] |
[[1, 3], [3, 1], [2, 3], [3, 2], [1, 2], [0, 0]] | [3, 3, 1, 1, 5, 6] |
입출력 예 설명
입출력 예 #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등은 없습니다.
이번 문제는 점수를 int형으로만 바라보았기에 실패하는 테스트케이스가 있었다.
생각해보나 평균점수 2와 2.5를 int로 구분할 수가 없는 것과 같이 소수점 차이로 인한 등수 차이를 구별하지 못했던 초기 코드를 수정했다.
using System;
using System.Collections.Generic;
public class Solution {
public int[] solution(int[,] score) {
int length = score.GetLength(0);
int[] answer = new int[length];
SortedDictionary<double, List<int>> sorted = new SortedDictionary<double, List<int>>();
for (int k = 0; k < length; k++) {
double totalScore = ((double)score[k,0] + score[k,1]) / 2;
if (!sorted.ContainsKey(totalScore))
sorted[totalScore] = new List<int>();
sorted[totalScore].Add(k);
}
foreach (var kvp in sorted) {
foreach (var total in kvp.Value)
answer[total] = length - kvp.Value.Count + 1;
length -= kvp.Value.Count;
}
return answer;
}
}
다음은 다른분이 작성해주신 Linq를 이용한 정렬 해결 방식이다.
가독성도 내 코드보다 좋고 더 빠르게 처리되는 점에서 배울점이 많아보인다.
using System;
using System.Linq;
using System.Collections.Generic;
public class Solution
{
public int[] solution(int[,] score)
{
List<int> scoreList = new List<int>();
List<int> rankList = new List<int>();
for(int i=0; i<score.GetLength(0); i++)
scoreList.Add(score[i, 0] + score[i, 1]);
List<int> sortScore = scoreList.OrderByDescending(x => x).ToList();
for(int i=0; i<sortScore.Count; i++)
rankList.Add(sortScore.FindIndex(x => x == scoreList[i]) + 1);
return rankList.ToArray();
}
}