C#/알고리즘 문제 풀기

프로그래머스 - 베스트 앨범

Toa_ 2025. 9. 12. 19:53

 

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

이번 문제는 노래의 인기순서 나열을 특정 조건하에 진행하는 문제이다.

이곳에서 중요한 조건은 기본적인 기준 1,2,3 를 지켜가며 중복되는 장르는 최대 2개까지만 넣을수 있는 제한이 있다는 점이다.

 

 

따라서 중복장르 2개 제한을 Dictionary<장르,int> 의 형식으로 (장르 이름 , 2)  value 값을 체크를 통해 중복관리,이후 정렬 기준을 3>2>1 순서대로 분류를 진행하여 우선순위에 맞춘 값을 도출했다.

 

 

 


 

 

 

public int[] solution(string[] genres, int[] plays)
{
    int[] answer = new int[] { };
    List<Tuple<string,int,int>> list = new List<Tuple<string,int,int>>(); // Tuple<장르 ,재생횟수, 고유번호>
    Dictionary<string,int> genreDict = new Dictionary<string,int>(); // 장르별 총합 재생횟수
    Dictionary<string, int> checkdDict = new Dictionary<string, int>(); // 장르별 누적 채택 횟수

    for(int i = 0; i < genres.Length; i++)
    {
        list.Add(new Tuple<string,int, int>(genres[i],plays[i], i));

        if (genreDict.ContainsKey(genres[i]))
            genreDict[genres[i]] += plays[i];
        else
        {
            genreDict.Add(genres[i], plays[i]);
            checkdDict.Add(genres[i], 2);
        }
    }
    list.Sort((a, b) => b.Item2.CompareTo(a.Item2)); // 재생횟수 내림차순 정렬
    var sortedGenre = genreDict.OrderByDescending(x => x.Value).Select(x => x.Key).ToList(); // 장르별 재생횟수 내림차순으로 list에 받아오기


    List<int> ans = new List<int>();
    for (int i = 0; i < sortedGenre.Count; i++)
    {
        for (int j = 0; j < genres.Length; j++)
        {
            if (list[j].Item1 == sortedGenre[i] && checkdDict[sortedGenre[i]] > 0)
            {
                ans.Add(list[j].Item3);
                checkdDict[sortedGenre[i]]--;
                if(checkdDict[sortedGenre[i]] == 0) break;
            }
        }
    }

    answer = ans.ToArray();
    return answer;
}

 

 

 

문제 자체는 재미있었고 생각할 거리도 많았지만 Linq의 활용능력이 아직은 부족한 편이라

Linq 메서드를 활용하여 체인 메서드 구조의 직관적인 형태로 구현하지 못한점이 아쉽다.