베스트앨범

Algorithm 2019. 8. 20. 16:08
반응형
  • 베스트앨범
  • darklight

    sublimevimemacs

    C# 

문제 설명

스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다.

  1. 속한 노래가 많이 재생된 장르를 먼저 수록합니다.
  2. 장르 내에서 많이 재생된 노래를 먼저 수록합니다.
  3. 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다.

노래의 장르를 나타내는 문자열 배열 genres와 노래별 재생 횟수를 나타내는 정수 배열 plays가 주어질 때, 베스트 앨범에 들어갈 노래의 고유 번호를 순서대로 return 하도록 solution 함수를 완성하세요.

제한사항

  • genres[i]는 고유번호가 i인 노래의 장르입니다.
  • plays[i]는 고유번호가 i인 노래가 재생된 횟수입니다.
  • genres와 plays의 길이는 같으며, 이는 1 이상 10,000 이하입니다.
  • 장르 종류는 100개 미만입니다.
  • 장르에 속한 곡이 하나라면, 하나의 곡만 선택합니다.
  • 모든 장르는 재생된 횟수가 다릅니다.

입출력 예

genresplaysreturn

[classic, pop, classic, classic, pop] [500, 600, 150, 800, 2500] [4, 1, 3, 0]

입출력 예 설명

classic 장르는 1,450회 재생되었으며, classic 노래는 다음과 같습니다.

  • 고유 번호 3: 800회 재생
  • 고유 번호 0: 500회 재생
  • 고유 번호 2: 150회 재생

pop 장르는 3,100회 재생되었으며, pop 노래는 다음과 같습니다.

  • 고유 번호 4: 2,500회 재생
  • 고유 번호 1: 600회 재생

따라서 pop 장르의 [4, 1]번 노래를 먼저, classic 장르의 [3, 0]번 노래를 그다음에 수록합니다.

※ 공지 - 2019년 2월 28일 테스트케이스가 추가되었습니다.

 

 

https://medium.com/@nsh235482/java-coding-programmers-hash-lv3-%EB%B2%A0%EC%8A%A4%ED%8A%B8-%EC%95%A8%EB%B2%94-278fa3ad4d9c

 

[JAVA] 프로그래머스 : Hash Lv3. 베스트 앨범

[문제]

medium.com

 

C#

...더보기

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
 
public class Solution // 베스트엘범
{
    public int[] solution(string[] genres, int[] plays)
    {
        List<int> lstAnswer = new List<int>();
 
        List<MusicInfo> lst = new List<MusicInfo>();
 
        for (int i = 0; i < genres.Count(); i++)
        {
            lst.Add(new MusicInfo(i, genres[i], plays[i]));
        }
 
        var query = (from m in lst
                    group m by m.Genre into g
                    select new {
                        genre = g.First().Genre,
                        playSum = g.Sum(x => x.Plays)
                    }).OrderByDescending(x => x.playSum);
 
 
        foreach (var hitGenre in query)
        {
            // 장르별 두건 추출
            var query2 = (from m in lst
                          where m.Genre == hitGenre.genre
                          orderby m.Plays descending
                          select m).Take(2);
            foreach (var pick in query2)
            {
                lstAnswer.Add(pick.Index);
            }
        }
 
        return lstAnswer.ToArray();
    }
}
 
public class MusicInfo
{
    public int Index { set; get; }
    public string Genre { set; get; }
    public int Plays { set; get; }
 
    public MusicInfo(int p_Index, string p_Genre, int p_Plays)
    {
        this.Index = p_Index;
        this.Genre = p_Genre;
        this.Plays = p_Plays;
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Collections.Generic;
 
public class Solution {
 
    public struct Item
    {
        public int index;
        public int play;
 
    };
 
    public int[] solution(string[] genres, int[] plays) {
        List<int> answers = new List<int>();
        Dictionary<stringint> my_dict = new Dictionary<stringint>();
 
        Dictionary<stringList<Item>> my_dict2 = new Dictionary<stringList<Item>>();
 
        for (int i = 0; i < genres.Length; i++)
        {
            Item item = new Item();
            item.index = i;
            item.play = plays[i];
 
            if (my_dict.ContainsKey(genres[i]) == false)
            {
                my_dict.Add(genres[i], plays[i]);
                my_dict2.Add(genres[i], new List<Item>() { item });
 
            }
            else
            {
                my_dict[genres[i]] += plays[i];
                my_dict2[genres[i]].Add(item);
            }
        }
 
        List<string> generList = new List<string>(my_dict.Keys);
 
        generList.Sort((l, r) =>
        {
            if (my_dict[l] > my_dict[r])
            {
                return -1;
            }
            else if (my_dict[l] < my_dict[r])
            {
                return 1;
            }
            else
            {
                return 0;
            }
        });
 
        for (int i = 0; i < generList.Count; i++)
        {
            string gener = generList[i];
            var list = my_dict2[gener];
 
            list.Sort((l, r) =>
            {
            if (l.play > r.play)
                return -1;
            else if (l.play < r.play)
                    return 1;
                else
                    return 0;
            });
 
            answers.Add(list[0].index);
 
            if (list.Count >= 2)
            {
                answers.Add(list[1].index);
            }
        }
 
        return answers.ToArray();
    }
}
 
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
using System.Collections.Generic;
 
public class Solution
{
    public int[] solution(string[] genres, int[] plays)
    {
        List<int> answer = new List<int>{ };
        Dictionary<string, Album> dic = new Dictionary<string, Album>();
 
        for (int i = 0; i < genres.Length; i++){
            if(dic.ContainsKey(genres[i])){
                dic[genres[i]].AddInfo(plays[i] , i);
            }
            else{
                dic.Add(genres[i], new Album());
                dic[genres[i]].AddInfo(plays[i] , i);
            }
        }
        List<string> priority = new List<string>();
 
        foreach(var item in dic){
            if(priority.Count > 0){
                bool find = false;
                for (int i = 0; i < priority.Count; i++)
                {
                    if (item.Value.sum > dic[priority[i]].sum){
                        priority.Insert(i , item.Key);
                        find = true;
                        break;
                    }
                }
                if(find == false){
                    priority.Add(item.Key);
                }
            }
            else{
                priority.Add(item.Key);
            }
        }
 
        for (int i = 0; i < priority.Count; i++)
        {
            if(dic[priority[i]].plays.Count > 1){
                answer.Add(dic[priority[i]].secondIndex);
            }
        }
 
        return answer.ToArray();
    }
    public class Album{
 
        public long sum;
        public int firstIndex = -1;
        public int secondIndex = -2;
 
        public Dictionary<int , int> plays = new Dictionary<int , int>();
 
        public void AddInfo(int i , int uId){
            plays.Add(uId,i);
            sum += i;
            if(plays.ContainsKey(firstIndex) && plays.ContainsKey(secondIndex))
            {
                if (plays[firstIndex] < i)
                {
                    secondIndex = firstIndex;
                    firstIndex = uId;
                }
                else if (plays[secondIndex] < i)
                {
                    secondIndex = uId; 
                }
            }
            else{
                if (plays.ContainsKey(firstIndex) == false)
                {
                    firstIndex = uId;
                }
                else if (plays.ContainsKey(secondIndex) == false)
                {
                    if(i > plays[firstIndex])
                    {
                        secondIndex = firstIndex;
                        firstIndex = uId;
                    }
                    else{
                        secondIndex = uId;
                    }
                }
            }
        }
 
    }
 
}
 
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
 
public class Solution {
    public int[] solution(string[] genres, int[] plays) {
        Dictionary<stringint> genreCounter = new Dictionary<stringint>(100);
        Dictionary<stringList<int>> genreList = new Dictionary<stringList<int>>(100);
        List<string> genresCountList = new List<string>(100);
        for(int i = 0; i < genres.Length; i++){
            string genre = genres[i];
            if(genreCounter.ContainsKey(genre)){
                genreCounter[genre] += plays[i];
                genreList[genre].Add(i);
            }
            else{
                genreCounter.Add(genre, plays[i]);
                genreList.Add(genre, new List<int>(new int[]{i}));
                genresCountList.Add(genre);
            }
        }
        genresCountList.Sort((string a, string b)=>{
            return genreCounter[b] - genreCounter[a];
        });
        int answerLength = 0;
        foreach(var gList in genreList.Values){
            if(gList.Count < 2){
                answerLength += gList.Count;
            }
            else{
                answerLength += 2;
                gList.Sort((int a, int b)=>{
                   if(plays[a] != plays[b])
                       return plays[b] - plays[a];
                    return a - b;
                });
            }
        }
        int[] answer = new int[answerLength];
        int idx = 0;
        foreach(string genre in genresCountList){
            for(int i = 0; i < genreList[genre].Count && i < 2; i++){
                answer[idx++= genreList[genre][i];
            }
        }
 
        return answer;
    }
 
}
 
 
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using System.Linq;
 
public class Solution {
    public int[] solution(string[] genres, int[] plays) {
        Dictionary<stringList<int>> dic = new Dictionary<stringList<int>>();
 
        for (int i = 0; i < genres.Length; i++)
        {
            if (dic.ContainsKey(genres[i]) == true)
            {
                dic[genres[i]].Add(i);
            }
            else
            {
                dic.Add(genres[i], new List<int>());
                dic[genres[i]].Add(i);
            }
        }
 
        List<List<int>> range = new List<List<int>>(dic.Values);
 
        range.Sort((x, y) =>
        {
            int n1 = x.Sum(e => plays[e]);
            int n2 = y.Sum(e => plays[e]);
 
            return n2.CompareTo(n1);
        });
 
        List<int> answer = new List<int>();
        foreach (List<int> item in range)
        {
            item.Sort((x, y) =>
            {
                return plays[y].CompareTo(plays[x]);
            });
 
            for (int i = 0; i < item.Count && i < 2; i++)
            {
                answer.Add(item[i]);
            }
        }
 
        return answer.ToArray();
    }
}
 
 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
public class Solution {
    public int[] solution(string[] genres, int[] plays) {
 
            int[] answer = new int[] { };
 
            if (genres == null || plays == null || genres.Length != plays.Length)
                return answer;
 
            //Dictionary<string, int[]> dic = new Dictionary<string, int[]>();
            Dictionary<stringint> dicSum = new Dictionary<stringint>();
 
            Dictionary<stringList<int>> dicTop2 = new Dictionary<string,List<int>>();
 
            for (int n = 0; n < genres.Length; n++)
            {
                string sGenres = genres[n];
 
                if (!dicSum.ContainsKey(sGenres))
                {
                    //dic.Add(sGenres, new int[2]);
                    dicSum.Add(sGenres, plays[n]);
                    dicTop2.Add(sGenres, new List<int>() { n });
                }
                else
                {
                    //dic[sGenres][0] = n;
                    //dic[sGenres][1] = plays[n];
                    dicSum[sGenres] += plays[n];
 
                    for (int nTop = 0; nTop < 2; nTop++)
                    {
 
 
                        if (plays[dicTop2[sGenres][nTop]] < plays[n])
                        {
                            dicTop2[sGenres].Insert(nTop, n);
                            break;
                        }
 
                        if (dicTop2[sGenres].Count <= nTop + 1)
                        {
                            dicTop2[sGenres].Add(n);
                            break;
                        }
                    }
 
 
                }
            }
 
            List<int> ans = new List<int>();
            foreach (string key in dicSum.OrderByDescending(p => p.Value).ToDictionary(p => p.Key).Keys)
            {
                int cnt = 0;
                foreach (int order in dicTop2[key])
                {
                    ans.Add(order);
                    cnt++;
 
                    if (cnt >= 2break;
                }
            }
 
            answer = ans.ToArray();
 
            return answer;
    }
}
 
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Collections.Generic;
using System.Linq;
 
public class Solution {
    class Song
        {
            public string _genres;
            public int playTime;
            public int priority;
        }
     public int[] solution(string[] genres, int[] plays)
        {
 
            int[] answer = new int[] { };
            Dictionary<stringint> keyValuePairs_TotalCountPlays = new Dictionary<stringint>();
            List<Song> songList = new List<Song>();
 
            for(int i = 0;i<genres.Length;i++)
            {
                songList.Add(new Song { _genres = genres[i], playTime = plays[i], priority = i });
            }
 
            //전체 합계를 구함
            for (int i = 0; i < genres.Length; i++)
            {
                if (!keyValuePairs_TotalCountPlays.ContainsKey(genres[i]))
                {
                    keyValuePairs_TotalCountPlays[genres[i]] = plays[i];
                }
                else
                {
                    keyValuePairs_TotalCountPlays[genres[i]] += plays[i];
                }
            }
            answer = new int[keyValuePairs_TotalCountPlays.Count*2];
 
            var descendingTotalPlayList = keyValuePairs_TotalCountPlays.OrderByDescending(num => num.Value);
            songList.Sort(delegate (Song x,Song y)
            {
                int cmp = 0;
 
                cmp = y._genres.CompareTo(x._genres);
                if(cmp==0)
                {
                    cmp = y.playTime.CompareTo(x.playTime);
                }
 
                if(cmp==0)
                {
                    cmp = x.priority.CompareTo(y.priority);
                }
 
                return cmp;
            });
 
 
            List<Song> sortedSongList = new List<Song>();
            foreach (var buf in descendingTotalPlayList)
            {
                sortedSongList.AddRange(songList.FindAll((x) => x._genres == buf.Key).GetRange(0, songList.FindAll((x) => x._genres == buf.Key).Count == 1 ? 1 : 2));
                if(songList.FindAll((x)=>x._genres ==buf.Key).Count==1)
                {
                    answer = new int[answer.Count() - 1];
                }
            }
 
            int j = 0;
            foreach(var buf in sortedSongList)
            {
                answer[j] = buf.priority;
                j++;
            }
 
            return answer;
        }
}
 
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
using System;
using System.Collections;
using System.Collections.Generic;
public class Solution {
    public int[] solution(string[] genres, int[] plays)
    {
        Dictionary<stringList<Song>> bestAlbum = new Dictionary<stringList<Song>>();
        Dictionary<stringint> genresTotalCount = new Dictionary<stringint>();
        Queue genresQueue = new Queue();
        for (int i = 0; i< genres.Length; i++)
        {
            if(bestAlbum.ContainsKey(genres[i]))
            {
                bestAlbum[genres[i]].Add(new Song(genres[i],i, plays[i]));
            }
            else
            {
                var newList = new List<Song>();
                newList.Add(new Song(genres[i],i, plays[i]));
                bestAlbum.Add(genres[i], newList);
                genresTotalCount.Add(genres[i], 0);
            }
        }
 
        foreach(var playList in bestAlbum.Keys)
        {
            int totalCount = 0;
            foreach(var song in bestAlbum[playList])
            {
                totalCount += song.PlayCount;
            }
            SortSong(bestAlbum[playList]);
            genresTotalCount[playList] = totalCount;
        }
 
        while(genresTotalCount.Count != 0)
        {
            int checkCount =0;
            string findKey = string.Empty;
            foreach (var playList in genresTotalCount.Keys)
            {
                if(genresTotalCount[playList] > checkCount)
                {
                    checkCount = genresTotalCount[playList];
                    findKey = playList;
                }
            }
 
            genresQueue.Enqueue(bestAlbum[findKey]);
            genresTotalCount.Remove(findKey);
        }
 
        List<int> answer = new List<int>();
        int limit = 2;
        while (genresQueue.Count != 0)
        {
            List<Song> songList = (List<Song>)genresQueue.Dequeue();
            int currentLimit = 0;
            foreach (var song in songList)
            {
                if(limit <= currentLimit)
                {
                    break;
                }
                answer.Add(song.ID);
                currentLimit++;
            }
 
        }
        return answer.ToArray();
    }
 
    void SortSong(List<Song> songList )
    {
        for(int i = 0; i< songList.Count-1; i++)
        {
            for(int j = 0; j< songList.Count -1 - i; j++)
            {
                if(Check(songList[j] , songList[j + 1] , 0))
                {
                    var tempValue = songList[j+1];
                    songList[j+1= songList[j];
                    songList[j] = tempValue;
                }
            }
 
        }
 
    }
 
    bool Check(Song left , Song right, int depth)
    {
        switch (depth)
        {
            case 0:
                if (left.PlayCount < right.PlayCount)
                {
                    return true;
                }
                else if(left.PlayCount == right.PlayCount)
                {
                    return Check(left, right, depth + 1);
                }
                break;
            case 1:
                if (left.ID > right.ID )
                {
                    return true;
                }
                return false;
        }
        return false;
 
 
    }
 
    class Song
    {
        private int _id;
        private int _playCount;
        private string _genres;
        private int _totalCount;
 
        public int ID
        {
            get
            {
                return _id;
            } 
        }
 
        public int PlayCount
        {
            get
            {
                return _playCount;
            }
        }
 
 
        public int TotalCount
        {
            set
            {
                _totalCount = value;
            }
            get
            {
                return _totalCount;
            }
        }
 
        public string Genres
        {
            get
            {
                return _genres;
            }
        }
 
 
        public Song(string genres , int id , int playCount)
        {
            _genres = genres;
            _id = id;
            _playCount = playCount;
            _totalCount = playCount;
        }
    }
}
 
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using System;
using System.Collections.Generic;
using System.Linq;
 
public class Solution {
    public int[] solution(string[] genres, int[] plays) {
        Songs songs = ConvertType(genres: genres, plays: plays);
        SongsDic songsDic = GroupByGenre(songs: songs);
        IEnumerable<string> genreOrderBy = songs.GroupBy(song => song.Genre).OrderByDescending(group => group.Sum(song => song.PlayCount)).Select(group => group.Key);
 
            List<int> answers = GetAnswer(songsDic: songsDic, genres: genreOrderBy);
 
        // int[] answer = new int[] {};
        return answers.ToArray();
    }
 
 
    Songs ConvertType(string[] genres, int[] plays)
    {
        Songs songs = new Songs();
 
        for (int i = 0; i < genres.Length; i++)
        {
            Console.WriteLine("id: {0}, genre: {1}, count: {2}", i, genres[i], plays[i]);
            songs.Add(new Song(id: i, playCount: plays[i], genre: genres[i]));
        }
 
        return songs;
    }
 
    SongsDic GroupByGenre(Songs songs)
    {
        SongsDic songsDic = new SongsDic();
 
        foreach (var group in songs.GroupBy(song => song.Genre))
        {
            Console.WriteLine("genre: {0}, count: {1}"group.Key, group.Count());
            songsDic.Add(group.Key, new Songs(group.OrderByDescending(song => song.PlayCount).ThenBy(song => song.ID)));
        }
 
        return songsDic;
    }
 
 
        List<int> GetAnswer(SongsDic songsDic, IEnumerable<string> genres)
        {
            List<int> answer = new List<int>();
 
            foreach (string genre in genres)
            {
                Songs songs = songsDic[genre];
 
                Songs top = songs.Count > 1 ? new Songs(songs.GetRange(02)) : new Songs(songs[0]);
 
                foreach (Song song in top)
                {
                    answer.Add(song.ID);
                }
            }
 
            return answer;
        }
 
    public struct Song
    {
        public int ID;
        public int PlayCount;
        public string Genre;
 
        public Song(int id, int playCount, string genre)
        {
            ID = id;
            PlayCount = playCount;
            Genre = genre;
        }
    }
 
    public class Songs : List<Song>
    {
        public Songs()
        {
 
        }
 
        public Songs(Song song)
        {
            this.Add(song);
        }
 
        public Songs(IEnumerable<Song> songs)
        {
            this.AddRange(songs);
        }
    }
 
    public class SongsDic : Dictionary<string, Songs>
    {
        public SongsDic()
        {
 
        }
    }
}
 
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System;
using System.Collections.Generic;
using System.Linq;
 
public class Solution {
    public int[] solution(string[] genres, int[] plays) {
        Songs songs = ConvertType(genres: genres, plays: plays);
        SongsDic songsDic = GroupByGenre(songs: songs);
        IEnumerable<string> genreOrderBy = songs.GroupBy(song => song.Genre).OrderByDescending(group => group.Sum(song => song.PlayCount)).Select(group => group.Key);
 
        List<int> answers = GetAnswers(songsDic: songsDic, genres: genreOrderBy);
 
        return answers.ToArray();
    }
 
 
    Songs ConvertType(string[] genres, int[] plays)
    {
        Songs songs = new Songs();
 
        for (int i = 0; i < genres.Length; i++)
        {
            songs.Add(new Song(id: i, playCount: plays[i], genre: genres[i]));
        }
 
        return songs;
    }
 
    SongsDic GroupByGenre(Songs songs)
    {
        SongsDic songsDic = new SongsDic();
 
        foreach (var group in songs.GroupBy(song => song.Genre))
        {
            songsDic.Add(group.Key, new Songs(group.OrderByDescending(song => song.PlayCount).ThenBy(song => song.ID)));
        }
 
        return songsDic;
    }
 
    List<int> GetAnswers(SongsDic songsDic, IEnumerable<string> genres)
    {
        List<int> answers = new List<int>();
 
        foreach (string genre in genres)
        {
            foreach (Song song in songsDic[genre].Take(2))
            {
                answers.Add(song.ID);
            }
        }
 
        return answers;
    }
 
    public struct Song
    {
        public int ID;
        public int PlayCount;
        public string Genre;
 
        public Song(int id, int playCount, string genre)
        {
            ID = id;
            PlayCount = playCount;
            Genre = genre;
        }
    }
 
    public class Songs : List<Song>
    {
        public Songs()
        {
 
        }
 
        public Songs(Song song)
        {
            this.Add(song);
        }
 
        public Songs(IEnumerable<Song> songs)
        {
            this.AddRange(songs);
        }
    }
 
    public class SongsDic : Dictionary<string, Songs>
    {
        public SongsDic()
        {
 
        }
    }
}
 
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Collections.Generic;
using System.Linq;
 
public class Solution {
    public int[] solution(string[] genres, int[] plays) {
        int[] answer = new int[] {};
        List<Music> musicList = new List<Music>();
        List<int> rank = new List<int>();
 
        for (int i = 0; i < genres.Length; i++)
        {
            Music music = new Music();
            music.seq = i;
            music.genre = genres[i];
            music.play = plays[i];
            musicList.Add(music);
        }
 
        var musicGroupList = from m in musicList.OrderByDescending(s => s.play).ThenBy(s => s.seq)
            group m by m.genre into g
            orderby g.Sum(s => s.play) descending
            select g;
 
        foreach (var musicGroup in musicGroupList)        
        {
            foreach (var item in musicGroup.Take(2))
            {
                rank.Add(item.seq);
            }
        }
 
        answer = rank.ToArray();
 
        return answer;
    }
 
    private class Music
    {
        public int seq { get; set; }
        public string genre { get; set; }
        public int play { get; set; }
    }
}
 
 

 

 

 

javascript 

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function solution(genres, plays) {
    var songs = 
        genres.map((genre, index) => {
            return {
                no: index,
                genre: genre,
                playCount: plays[index]    
            };
        });
 
    var genrePlayCount = [];
    songs.forEach(song => {
        var thisGenre = genrePlayCount.find(genrePlay => genrePlay.genre === song.genre);
        if (!thisGenre) {
            genrePlayCount.push({
                genre: song.genre, totalPlayCount: song.playCount
            });
        } else {
            thisGenre.totalPlayCount += song.playCount;
        }
    });
 
    genrePlayCount.sort((a, b) => b.totalPlayCount - a.totalPlayCount);
 
    var answer = [];
    genrePlayCount.forEach(genrePlay => {
        var thisGenreSongs = songs.filter(song => genrePlay.genre === song.genre);
        thisGenreSongs.sort((a, b) => b.playCount - a.playCount);
        answer.push(thisGenreSongs[0].no);
        if (thisGenreSongs.length > 1) {
            answer.push(thisGenreSongs[1].no);
        }
    });
 
    return answer;
}
 
 
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function solution(genres, plays) {
    const genreObj = {};
    genres.forEach((genre, index) => {
        if (!genreObj[genre]) {
            genreObj[genre] = [
                {
                    index,
                    count: plays[index],
                }
            ];
        } else {
            genreObj[genre].push({ index, count:plays[index], });
            genreObj[genre].sort((a, b) => a.count === b.count ? a.index - b.index : b.count - a.count);
        }
    })
    const genreChart = Object.keys(genreObj).sort((a, b) => {
        const countSumA = genreObj[a].reduce((acc, value) => acc + value.count, 0);
        const countSumB = genreObj[b].reduce((acc, value) => acc + value.count, 0);
        return countSumB - countSumA;
    })
    const answer = [];
    genreChart.forEach(genre => {
        if (genreObj[genre].length === 1) {
            answer.push(genreObj[genre][0].index);
        } else {
            answer.push(genreObj[genre][0].index);
            answer.push(genreObj[genre][1].index);
        }
    })
    console.log(answer);
    return answer;
}
 
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
function solution(genres, plays) {
    // 장르와 재생수를 객체로 묶는다.
    const songs = genres.map((item, index) => {
      return { genres: item, plays: plays[index], id: index }}
    );
 
 
    // 장르 중복값 제거
    const uniqGenres = genres.reduce((accumulator, currentValue) => {
      if (accumulator.indexOf(currentValue) < 0 ) accumulator.push(currentValue);
      return accumulator;
    },[]);
 
    // 1. 속한 노래가 많이 재생된 장르를 먼저 수록합니다.
    const sumPlays = uniqGenres.map(genres => {
      const tempGenres = songs.filter(song => song.genres === genres);
        return accumulator + currentValue.plays;
      }), 0);
      return { genres, plays: sum };
    });
 
    // plays 기준으로 정렬
    sumPlays.sort(function (a, b) {
      if (a.plays > b.plays) {
        return -1;
      }
      if (a.plays < b.plays) {
        return 1;
      }
      // a must be equal to b
      return 0;
    });
 
    // 2. 장르 내에서 많이 재생된 노래를 먼저 수록합니다.
    // 3. 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다.
    const mostPopularSongs = sumPlays.map(genres => {
      return songs
        .filter(song => song.genres === genres.genres)
        .sort(function (a, b) {
          if (a.plays > b.plays) {
            return -1;
          }
          if (a.plays < b.plays) {
            return 1;
          }
          if (a.id > b.id) {
            return 1;
          }
          if (a.id < b.id) {
            return -1
          }
          return 0;
        })
        .filter((song, index) => index < 2);
    });
    const answer = [];
    mostPopularSongs.forEach(genres => {
      genres.forEach(song => {
        answer.push(song.id);
      })
    });
    return answer;
}
 
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function solution(genres, plays) {
    var dic = {};
    genres.forEach((t,i)=> {
        dic[t] = dic[t] ?  dic[t] + plays[i] :plays[i];        
    });
 
    var dupDic = {};
    return genres          
          .map((t,i)=> ({genre : t, count:plays[i] , index:i}))
          .sort((a,b)=>{               
               if(a.genre !== b.genre) return dic[b.genre] - dic[a.genre];
               if(a.count !== b.count) return b.count - a.count;
               return a.index - b.index;
           })
           .filter(t=>  {
               if(dupDic[t.genre] >= 2return false;
               dupDic[t.genre] = dupDic[t.genre] ? dupDic[t.genre]+ 1 : 1;
               return true;
            })
           .map(t=> t.index);    
}
 
 
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function solution(genres, plays) {
    const count = {};
    let answer = [];
    const acc = genres.reduce((a, c, i) => {
        debugger;
        count[c] ? count[c].push([i, plays[i]]) : count[c] = [[i, plays[i]]];
        return a.set(c, a.get(c) ? a.get(c) + plays[i] : plays[i]), a;
    }, new Map());
 
    [...acc].sort((a, b) => b[1- a[1]).map(v => {
            answer = answer.concat(count[v[0]].sort((c, d)=>d[1]-c[1]).slice(0,2));
    });
    return answer.map(v=>v[0]);
}
 
 

 

반응형

'Algorithm' 카테고리의 다른 글

프로그래머스 | N개의 최소공배수  (0) 2019.08.22
LeetCode | Two Sum  (0) 2019.08.21
위장  (0) 2019.08.20
전화번호 목록  (0) 2019.08.20
완주하지 못한 선수  (0) 2019.08.20
: