CHashtag

[프로그래머스] [C#] 모의고사 본문

알고리즘

[프로그래머스] [C#] 모의고사

HyoSeong 2021. 6. 30. 23:02
반응형

안녕하세요.

오늘은 프로그래머스 코딩테스트 연습 문제인 "모의고사" 를 풀어 보았습니다.

 

 

문제 링크


https://programmers.co.kr/learn/courses/30/lessons/42840

 

 

문제 풀이 방법


불필요한 변수 사용을 줄이기 위해 % (나머지) 연산자를 이용하여 변수 하나로 수포자 3명의 값을 비교하도록 하였습니다.

또한 Linq를 이용하여 최고 점수를 받은 사람들을 return하도록 구현하였습니다.

 

그 결과 평균 약 4.5ms 정도의 속도로 테스트를 통과하였습니다.

 

코드


using System.Collections.Generic;
using System.Linq;

public class Solution
{
    public int[] solution(int[] answers)
    {
        int[] supoja1 = new int[] { 1, 2, 3, 4, 5 };
        int[] supoja2 = new int[] { 2, 1, 2, 3, 2, 4, 2, 5 };
        int[] supoja3 = new int[] { 3, 3, 1, 1, 2, 2, 4, 4, 5, 5 };

        Dictionary<int, int> result = new Dictionary<int, int>()
        {
            {1,0 },
            {2,0 },
            {3,0 }
        };

        for(int i=0; i < answers.Length; i++)
        {
            if (supoja1[i % supoja1.Length] == answers[i]) result[1]++;
            if (supoja2[i % supoja2.Length] == answers[i]) result[2]++;
            if (supoja3[i % supoja3.Length] == answers[i]) result[3]++;
        }

        return result
            .Where(x => x.Value == result.Max(y => y.Value)) // Max값과 동일한 놈들만 고르면 자동으로 오름차순 되어있다.
            .Select(x => x.Key) // 여기서 Key만 뽑아주고
            .ToArray(); // Array로 변환하여 return
    }
}

 

감사합니다.

반응형