알고리즘/프로그래머스
99클럽 코테 스터디 20일차 TIL (42840번: 모의고사)
Sondho
2024. 11. 17. 09:30
문제
https://school.programmers.co.kr/learn/courses/30/lessons/42840
학습 키워드
- 완전 탐색
풀이 및 코드
수포자가 찍는 방식에는 규칙이 있으므로 해당 규칙 순서대로 주어진 answer의 길이만큼 값을 할당받을 수 있도록 한다.
supoXXX : x번 수포자가 찍는 방식의 규칙
xxxIndex : x번 수포자가 찍은 숫자의 현재 인덱스. 1을 증가시킬 때마다 % supo.length를 해서 반복할 수 있도록 한다.
값을 다 할당했다면 주어진 answers를 순회하면서 각 수포자가 몇 점인지 계산한다.
import java.util.*;
class Solution {
private static int[] supoOne = new int[]{1, 2, 3, 4, 5};
private static int[] supoTwo = new int[]{2, 1, 2, 3, 2, 4, 2, 5};
private static int[] supoThree = new int[]{3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
public int[] solution(int[] answers) {
int answerSize = answers.length;
int[] supoes = new int[3];
int oneIndex = 0;
int twoIndex = 0;
int threeIndex = 0;
for (int i = 0; i < answerSize; i++) {
if (supoOne[oneIndex] == answers[i]) {
supoes[0]++;
}
if (supoTwo[twoIndex] == answers[i]) {
supoes[1]++;
}
if (supoThree[threeIndex] == answers[i]) {
supoes[2]++;
}
oneIndex = (oneIndex + 1) % supoOne.length;
twoIndex = (twoIndex + 1) % supoTwo.length;
threeIndex = (threeIndex + 1) % supoThree.length;
}
int max = Math.max(supoes[0], Math.max(supoes[1], supoes[2]));
List<Integer> answer = new ArrayList<>();
for (int i = 0; i < 3; i++) {
if (supoes[i] == max) {
answer.add(i + 1);
}
}
return answer.stream()
.mapToInt(Integer::intValue)
.toArray();
}
}