개?발/프로그래머스

모의고사 (C#)

YUEIC 2024. 4. 30. 18:49

 

학생 각각이 가진 패턴을 갖고 정답목록을 탐색하며 점수를 매긴다.

그리고 맞힌 개수가 가장 많은 학생순서를 출력한다.

이때 가장 많이 맞힌 개수가 같다면 학생순서를 오름차순으로 정렬해서 출력해야한다.

 

 

학생별 패턴을 분석하여 채점하는 방식은 위와 비슷하게 구현했다.

정답배열이 끝날때까지 학생별 패턴 배열을 반복시켜가며 비교하고

비교한 부분이 일치할 때 미리 생성해둔 studentScore이라는 요소가 3인 배열에

순차적으로(0=첫번째, 1=두번째, 2=세번째 학생) 카운트가 된다.

 

생각보다 이 오름차순이 잘 생각이 안나서 애먹었다.

결국 생각해낸건 

점수배열에서 가장 큰 값을 가져오고 

점수배열을 순차적으로 탐색하며 비교해 점수가 일치하면

인덱스를 리스트에 Add 하는 방식으로 했다.

이렇게 하면 점수배열이 중복되는 학생을 바로 오름차순(index 오름차순)으로 list에 정리가 된다.

이후 ToArray()를 통해 배열로 바꾼 뒤 값을 반환했다.

    public int[] solution(int[] answers) {
        int[] answer = new int[] {};

        List<int[]> student = new List<int[]>();

        student.Add(new int[] {1,2,3,4,5});
        student.Add(new int[] {2,1,2,3,2,4,2,5});
        student.Add(new int[] {3,3,1,1,2,2,4,4,5,5});

        int[] studentScore = new int[3];

        for( int i = 0; i < student.Count ; ++i){
            int cycle = 0;
            for(int j = 0 ; j < answers.Length; ++j){
                if(student[i].Length <= cycle){
                    cycle = 0;
                }
                if(student[i][cycle] == answers[j]){
                        studentScore[i]++;
                }
                cycle++;
            }
        }

        List<int> studentRank = new List<int>();

        for(int i = 0; i < studentScore.Length; ++i){
            if(studentScore[i] == studentScore.Max()){
                studentRank.Add(i+1);
            }
        }

        answer = studentRank.ToArray();

        return answer;
    }

'개?발 > 프로그래머스' 카테고리의 다른 글

소수만들기 (C#)  (1) 2024.05.01
문자열 내림차순으로 배치하기 (C#)  (0) 2024.05.01
카드 뭉치  (0) 2024.04.30
공원산책 (C#)  (0) 2024.04.29
달리기 경주  (1) 2024.04.26