답을 찍는 3가지 패턴과 정답이 주어질 때
3가지 패턴 중 정답을 가장 많이 맞힌 패턴을 오름차순 정렬하여 반환
public ArrayList<Integer> solution(int[] answers) {
int[] answer = new int[3];
int[] first = { 1, 2, 3, 4, 5 };
int[] second = { 2, 1, 2, 3, 2, 4, 2, 5 };
int[] third = { 3, 3, 1, 1, 2, 2, 4, 4, 5, 5 };
int firstScore = score(first,answers);
int secondScore = score(second,answers);
int thirdScore = score(third,answers);
int max = Math.max(secondScore, thirdScore);
max = Math.max(max, firstScore);
ArrayList<Integer> list = new ArrayList<Integer>();
if(max==firstScore) list.add(1);
if(max==secondScore) list.add(2);
if(max==thirdScore) list.add(3);
return list;
}
public int score(int[] person,int[] answers) {
int score = 0;
for (int i = 0; i < answers.length; i++) {
if(answers[i]==person[i%person.length])score++;
}
return score;
}
정답 개수 구하기
==> 패턴이 반복되기 때문에 %(패턴길이)로 패턴길이를 넘어가면 다시 앞으로 돌아와서 비교할 수 있게 한다.
최고점 구하여 1번부터 최고점과 같으면 list에 넣어 반환
만약 패턴이 많아진다면
score를 배열에 넣고 정렬로 최고점을 구한 후
반복문으로 list에 넣어 간결한 코드를 만들 수 있다.
'Java > Coding Test' 카테고리의 다른 글
문자열 나누기 문제 풀이 (1) | 2023.10.01 |
---|---|
대충 만든 자판 문제 풀이 (0) | 2023.10.01 |
개인정보 수집 유효 기간 문제 풀이 (0) | 2023.09.28 |
숫자 짝궁 문제 풀이 (1) | 2023.09.28 |
옹알이2 문제 풀이 (0) | 2023.09.28 |