코테/프로그래머스

[프로그래머스/C#]가장 많이 받은 선물

내꺼블로그 2024. 2. 13. 15:06

https://school.programmers.co.kr/learn/courses/30/lessons/258712?language=csharp

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

코드


using System;
using System.Collections.Generic;

public class Solution {
    public int solution(string[] friends, string[] gifts) {
        int answer = 0;
        List<List<int>> listGiveAndTake = new List<List<int>>();
        List<List<int>> listGift = new List<List<int>>();
        Dictionary<string, int> dicFriends = new Dictionary<string, int>();
        for(int i=0;i<friends.Length;i++){
            dicFriends.Add(friends[i], i);
            List<int> list1 = new List<int>();
            List<int> list2 = new List<int>();
            for(int j=0;j<3;j++){
                list2.Add(0);
            }
            listGift.Add(list2);
            for(int j=0;j<friends.Length;j++){
                list1.Add(0);
            }
            listGiveAndTake.Add(list1);
        }
        
        for(int i=0;i<gifts.Length;i++){
            string[] s = gifts[i].Split(' ');
            int idx1 = dicFriends[s[0]];
            int idx2 = dicFriends[s[1]];
            listGiveAndTake[idx1][idx2]++;
            listGift[idx1][0]++;
            listGift[idx2][1]++;
        }
        
        for(int i=0;i<listGift.Count;i++){
            listGift[i][2]=listGift[i][0]-listGift[i][1];
        }
        
        for(int i=0;i<listGiveAndTake.Count;i++){
            int temp = 0;
            for(int j=0;j<listGiveAndTake[i].Count;j++){
                if(i==j) continue;
                int f1 =listGiveAndTake[i][j];
                int f2 = listGiveAndTake[j][i];
                if(f1>f2){
                    temp++;
                }
                else if(f1==f2){
                    if(listGift[i][2]>listGift[j][2])
                        temp++;
                }
            }
            if(temp>answer) answer=temp;
        }
        return answer;
    }
}

 

 

 

풀이


문제에서 보여준 대로 행했다.(변수명 못 정하는 사람으로 이름이 개판이어도 용서바랍니댜,,,ㅠ)

listGiveAndTake는 행을 준 사람, 열을 받은 사람으로 두어 주고 받은 개수를 저장하도록 하였다.

listGift는 선물 지수를 저장하기 위한 행렬로 준 선물 개수, 받은 선물 개수, 선물 지수 순으로 저장되어 있다.

dicFriends는 행렬의 인덱스를 친구의 이름으로 관리하기 위해 선언한 Dictionary이다. 문자열 배열 friends에 저장되어 있는 친구의 이름을 key로 배열의 인덱스를 value로 저장하고 있다.

gifts를 순회하면서 친구 이름을 dicFriends를 사용하여 행렬의 인덱스에 접근해 값을 계산한다.

그 뒤 listGiveAndTake를 돌면서 (필요하다면 listGift에도 접근하면서) 선물을 몇 개 받을 수 있는지 구한다.

그 뒤 answer 값과 비교하여 더 큰 수를 answer에 대입하여 answer를 구한다.