-
프래그래머스 (Level 1) - 모의고사Coding Test/Coding Test 문제 풀이 2021. 12. 27. 12:10
문제 설명
풀이
int[] person01 = { 1, 2, 3, 4, 5 }; int[] person02 = { 2, 1, 2, 3, 2, 4, 2, 5 }; int[] person03 = { 3, 3, 1, 1, 2, 2, 4, 4, 5, 5 };
각각의 수포자가 문제를 찍는 방식을 배열로 저장한다.
for (int i = 0; i < answers.length; i++) { if (person01[i % person01.length] == answers[i]) point[0]++; if (person02[i % person02.length] == answers[i]) point[1]++; if (person03[i % person03.length] == answers[i]) point[2]++; }
문제의 정답이 저장된 배열 answers의 원소를 하나씩 탐색하면서, 각각의 수포자가 찍은 정답과 비교를 한다. 정답인 문제와 수포자들이 찍은 문제들을 비교하면서, 각각의 수포자들이 맞은 문제의 수를 카운트한다.
int max = Math.max(Math.max(point[0], point[1]), point[2]);
Math.max( ) 메서드를 사용하여 가장 높은 점수를 받은 사람(max)을 구한다.
List<Integer> list = new ArrayList<>(); if (max == point[0]) list.add(1); if (max == point[1]) list.add(2); if (max == point[2]) list.add(3);
높은 점수를 받은 사람이 여럿일 경우를 고려해야 하기 때문에, 가장 높은 점수와 각각의 수포자들이 맞은 점수를 비교하면서 max의 값과 동일한 수포자들을 골라낸다.
전체 소스코드
import java.io.*; import java.util.*; public class Solution08 { public int[] solution(int[] answers) { int[] person01 = { 1, 2, 3, 4, 5 }; int[] person02 = { 2, 1, 2, 3, 2, 4, 2, 5 }; int[] person03 = { 3, 3, 1, 1, 2, 2, 4, 4, 5, 5 }; int[] point = new int[3]; for (int i = 0; i < answers.length; i++) { if (person01[i % person01.length] == answers[i]) point[0]++; if (person02[i % person02.length] == answers[i]) point[1]++; if (person03[i % person03.length] == answers[i]) point[2]++; } int max = Math.max(Math.max(point[0], point[1]), point[2]); List<Integer> list = new ArrayList<>(); if (max == point[0]) list.add(1); if (max == point[1]) list.add(2); if (max == point[2]) list.add(3); int[] answer = new int[list.size()]; for (int i = 0; i < list.size(); i++) answer[i] = list.get(i); return answer; } }
코드 간소화
import java.io.*; import java.util.*; public class Solution08 { public int[] solution(int[] answers) { int[] person01 = { 1, 2, 3, 4, 5 }; int[] person02 = { 2, 1, 2, 3, 2, 4, 2, 5 }; int[] person03 = { 3, 3, 1, 1, 2, 2, 4, 4, 5, 5 }; int[] point = new int[3]; for (int i = 0; i < answers.length; i++) { if (person01[i % person01.length] == answers[i]) point[0]++; if (person02[i % person02.length] == answers[i]) point[1]++; if (person03[i % person03.length] == answers[i]) point[2]++; } int max = Math.max(Math.max(point[0], point[1]), point[2]); List<Integer> list = new ArrayList<>(); if (max == point[0]) list.add(1); if (max == point[1]) list.add(2); if (max == point[2]) list.add(3); return list.stream().mapToInt(i -> i.intValue()).toArray(); } }
return 문에서 list를 stream으로 중간처리를 한 후 배열 형태로 반환하는 방법이 있었다.
자바 스트림을 사용함으로써, 더 간단하고 직관적인 코드 구성이 가능했다.
728x90'Coding Test > Coding Test 문제 풀이' 카테고리의 다른 글
프로그래머스 (Level 2) - 기능개발 (0) 2021.12.28 프래그래머스 (Level 2) - 전화번호 목록 (0) 2021.12.28 프로그래머스 (Level 1) - K번째수 (0) 2021.12.27 프로그래머스 (Level 1) - 완주하지 못한 선수 (0) 2021.12.26 프로그래머스 (Level 1) - 소수 만들기 (0) 2021.12.26