BFS 알고리즘 포스팅에서 올렸던 내용을 다시 한 번 공부하기 위해 완전탐색 관련 문제를 풀어보았다.
SupoMan이라는 클래스를 추가로 만들어서 각 SupoMan 객체마다의 답안 순서와 맞춘 점수를 기록할 수 있도록 두 개의 필드를 만들어 주고 알맞은 값으로 초기화를 해주었다.
1. 이중 포문에서는 답안 순서대로 정답과 비교하며 맞을 경우 맞춘 점수를 + 1
2. 두번째 포문에서는 최대값을 구하기 위해 반복문 사용
3. 마지막 세번째 반복문에서는 각 객체의 맞춘 점수가 최대 점수와 같을 경우 해당 수포자를(인덱스 + 1) 리턴할 정답 리스트에 넣기
과정을 통해 풀이를 완료하였다.
MockTest.java
package com.example.Programmers.Lv1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* 프로그래머스 Lv1 - 모의고사
*/
public class MockTest {
public int[] solution(int[] answers) {
LinkedList<Integer> man1 = new LinkedList<>(Arrays.asList(1, 2, 3, 4, 5));
LinkedList<Integer> man2 = new LinkedList<>(Arrays.asList(2, 1, 2, 3, 2, 4, 2, 5));
LinkedList<Integer> man3 = new LinkedList<>(Arrays.asList(3, 3, 1, 1, 2, 2, 4, 4, 5, 5));
List<SupoMan> supoMans = Arrays.asList(new SupoMan(man1, 0), new SupoMan(man2, 0), new SupoMan(man3, 0));
for (int answer : answers) {
for (SupoMan supoMan : supoMans) {
Integer num = supoMan.man.poll();
if (answer == num) {
supoMan.score++;
}
supoMan.man.add(num);
}
}
int maxVal = Integer.MIN_VALUE;
for (SupoMan supoMan : supoMans) {
if (supoMan.score > maxVal) {
maxVal = supoMan.score;
}
}
List<Integer> answer = new ArrayList<>();
for (int i = 0; i < supoMans.size(); i++) {
if (supoMans.get(i).score == maxVal) {
answer.add(i + 1); // 인덱스를 넣는 것이 아닌 사람을 넣어야 하므로 +1
}
}
return answer.stream().mapToInt(Integer::intValue).toArray();
}
class SupoMan {
private Queue<Integer> man;
private Integer score;
public SupoMan(Queue<Integer> man, Integer score) {
this.man = man;
this.score = score;
}
}
}
MockTestTest.java
package com.example.Programmers.Lv1;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
public class MockTestTest {
@Test
public void testMockTest() {
MockTest mt = new MockTest();
int[] result1 = mt.solution(new int[] { 1, 2, 3, 4, 5 });
int[] result2 = mt.solution(new int[] { 1, 3, 2, 4, 2 });
assertArrayEquals(new int[] { 1 }, result1);
assertArrayEquals(new int[] { 1, 2, 3 }, result2);
}
}