728x90

문제

수포자 3명이 일정한 규칙으로 정답을 찍었을 때

가장 많은 문제를 맞힌 사람의 번호를 리턴하라

 

(동률인 경우에는 번호가 빠른 순으로 리턴한다.)

 

접근 방식

int[][] stupids = new int[][]{
    new int[]{1, 2, 3, 4, 5},
    new int[]{2, 1, 2, 3, 2, 4, 2, 5},
    new int[]{3, 3, 1, 1, 2, 2, 4, 4, 5, 5}
};

 

우선 각각의 수포자는 위와 같은 순서대로 문제를 찍으니

주어진 정답 배열을 순회하며 각 수포자의 찍기 규칙과 비교하며

맞힌 문제가 몇 개인지 카운트하고 가장 많이 맞힌 사람을 찾으면 된다.

 

주의해야 할 점은 정답 배열과 찍기 규칙의 길이가 다르기 때문에

찍는 순서가 마지막이 된 경우에는 배열의 인덱스를 다시 0으로 초기화 해줘야 하며,

동률인 경우에는 1, 2, 3번 수포자 순서대로 리턴해줘야 한다.

 

풀이

public class Main {

	public static void main(String[] args) {
		System.out.println(
			Arrays.toString(
				solution(new int[] {1, 2, 3, 4, 5})
			)
		);
		System.out.println(
			Arrays.toString(
				solution(new int[] {1, 3, 2, 4, 2})
			)
		);
	}

	private static int[] solution(int[] answers) {
		int[][] stupids = new int[][]{
			new int[]{1, 2, 3, 4, 5},
			new int[]{2, 1, 2, 3, 2, 4, 2, 5},
			new int[]{3, 3, 1, 1, 2, 2, 4, 4, 5, 5}
		};

		int[] scores = new int[stupids.length];
		int now = 0;

		List<Integer> list = new ArrayList<>();
		int max = -1;

		for (int[] arr : stupids) {
			int score = 0;
			int idx = 0;
			int length = arr.length;

			for (int answer : answers) {
				if (answer == arr[idx++]) {
					score++;
				}

				if (idx == length) {
					idx = 0;
				}
			}

			scores[now] = score;

			if (score > max) {
				max = score;
				list.clear();
				list.add(now + 1);
			} else if (score == max) {
				list.add(now + 1);
			}

			now++;
		}

		int[] result = new int[list.size()];

		for (int i = 0; i < list.size(); i++) {
			result[i] = list.get(i);
		}

		return result;
	}
}

 

+ Recent posts