주녘공부일지

[프로그래머스 C#] Lv.1 신고 결과 받기 본문

Programmers - C#/CodingTest Lv.1

[프로그래머스 C#] Lv.1 신고 결과 받기

주녘 2024. 2. 14. 16:47
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/92334

 

프로그래머스

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

programmers.co.kr

1. 정답코드 및 핵심 아이디어, 유의사항

신고자와 신고 대상에 대한 정보를 취합해 나온 정지 대상에 대해 기여한(?) 횟수를 구하는 문제

 

- 신고 정보 중에 중복되는 정보는 제외해야 함 (신고자와 신고 대상이 같을 경우)

-> bool타입 2차원 배열을 선언해 신고했다면 true로 바꿈으로써 중복되는 정보를 무시

 

주석 참조

    using System;
    using System.Collections.Generic;

    public class Solution
    {
        public int[] solution(string[] id_list, string[] report, int k)
        {
            int length = id_list.Length;
            int[] answer = new int[length];

            var dict = new Dictionary<string, int>(); // <이름, 아이디>
            var boolArrays = new bool[length, length]; // [신고자, 신고대상]

            // 아이디 사전 세팅
            for (int i = 0; i < length; i++)
                dict.Add(id_list[i], i);

            // 신고 처리
            for (int i = 0; i < report.Length; i++)
            {
                string[] strs = report[i].Split(' '); // [신고자, 신고대상]
                boolArrays[dict[strs[0]], dict[strs[1]]] = true; // 신고처리
            }

            // 신고 내용 취합 및 정지 처리
            for (int i = 0; i < length; i++) // i : 신고대상
            {
                int count = 0; // 누적 신고 개수

                for (int j = 0; j < length; j++) // j : 신고자
                    if (boolArrays[j, i])
                        count++;

                // 정지 대상이라면 신고자들에게 메일을 보냄
                if (count >= k)
                    for (int j = 0; j < length; j++)
                        if (boolArrays[j, i])
                            answer[j]++;
            }

            return answer;
        }
    }

 

+ System.Linq 네임스페이스를 적극 활용한 풀이 

    using System;
    using System.Linq;

    public class Solution
    {
        public int[] solution(string[] id_list, string[] report, int k)
        {
            var tReport = report.Distinct().
               Select(s => s.Split(' ')).
               GroupBy(g => g[1]).
               Where(w => w.Count() >= k).
               SelectMany(sm => sm.Select(s => s[0])).
               ToList();

            return id_list.ToDictionary(x => x, x => tReport.Count(c => x == c)).Values.ToArray();
        }
    }

 

728x90