코딩테스트/99클럽
99클럽 코테 스터디 15일차 TIL - 모의고사
꼽파
2024. 8. 5. 20:35
모의고사
출처 : 프로그래머스 Lv.1
문제 설명
- 수포자는 수학을 포기한 사람의 준말입니다. 수포자 삼인방은 모의고사에 수학 문제를 전부 찍으려 합니다. 수포자는 1번 문제부터 마지막 문제까지 다음과 같이 찍습니다.
- 1번 수포자가 찍는 방식: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
2번 수포자가 찍는 방식: 2, 1, 2, 3, 2, 4, 2, 5, 2, 1, 2, 3, 2, 4, 2, 5, ...
3번 수포자가 찍는 방식: 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, ... - 1번 문제부터 마지막 문제까지의 정답이 순서대로 들은 배열 answers가 주어졌을 때, 가장 많은 문제를 맞힌 사람이 누구인지 배열에 담아 return 하도록 solution 함수를 작성해주세요.
제한 조건
- 시험은 최대 10,000 문제로 구성되어있습니다.
- 문제의 정답은 1, 2, 3, 4, 5중 하나입니다.
- 가장 높은 점수를 받은 사람이 여럿일 경우, return하는 값을 오름차순 정렬해주세요.
입출력 예
answers | return |
[1,2,3,4,5] | [1] |
[1,3,2,4,2] | [1,2,3] |
풀이
function solution(answers) {
const hateMath1 = [1, 2, 3, 4, 5];
const hateMath2 = [2, 1, 2, 3, 2, 4, 2, 5];
const hateMath3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5];
let extendedArray = [];
let score1 = 0;
let score2 = 0;
let score3 = 0;
// hateMath의 배열 길이가 늘어나면 나머지를 활용하여 인덱스를 넣어줌.
// 만약 hateMath1가 반복된다고 할 때 i = 7인 경우
// 7 % 5 = 2이므로 hateMath1[2]인 3이 되어야 함.
// hateMath1 순회
for (let i = 0; i < answers.length; i++) {
if (i < hateMath1.length) {
if (answers[i] === hateMath1[i]) score1++;
} else {
extendedArray[i] = hateMath1[i % hateMath1.length];
if (answers[i] === extendedArray[i]) score1++;
}
}
extendedArray = []; // 초기화
// hateMath2 순회
for (let i = 0; i < answers.length; i++) {
if (i < hateMath2.length) {
if (answers[i] === hateMath2[i]) score2++;
} else {
extendedArray[i] = hateMath2[i % hateMath2.length];
if (answers[i] === extendedArray[i]) score2++;
}
}
extendedArray = []; // 초기화
// hateMath3 순회
for (let i = 0; i < answers.length; i++) {
if (i < hateMath3.length) {
if (answers[i] === hateMath3[i]) score3++;
} else {
extendedArray[i] = hateMath3[i % hateMath3.length];
if (answers[i] === extendedArray[i]) score3++;
}
}
// console.log(score1, score2, score3)
// T1 : 5 0 0
// T2 : 2 2 2
// 가장 큰 값을 기준으로 점수 3개를 각각 비교해줌.
// 비교 후 최댓값과 같은 값은 정답배열 안에 원소로 넣기
const MaxScore = Math.max(score1, score2, score3);
const answerArray = [];
if (score1 === MaxScore) answerArray.push(1);
if (score2 === MaxScore) answerArray.push(2);
if (score3 === MaxScore) answerArray.push(3);
return answerArray;
// 복잡도 : O(n) + O(n) + O(n) + O(1)
// => O(n)
}
수포자 1, 2, 3의 정답 패턴을 각각 hateMath 1, 2, 3배열로 만든다.
규칙적으로 반복하므로 배열의 원소를 순회하기 위함이다.
score1, 2, 3은 hateMath 1, 2, 3의 각 원소와 answers 배열의 원소가 일치할 경우 1점씩 증가하는 변수이다.
extendedArray는 answers의 길이가 hateMath 1, 2, 3보다 길 경우 더 반복해야할 원소값을 추가로 넣어주기 위해 만들어 놓았다.
이것은 비교용도로 쓰이기 때문에 hateMath 1, 2, 3을 순서대로 순회할 때마다 초기화를 해주어야 한다.
hateMath의 각 배열을 순회하는 방식은
1) hateMath 배열의 길이보다 작을 경우 : 단순 비교 후 score값을 증가시킨다.
2) 해당 배열의 길이를 넘어갈 경우 : 나머지 값을 이용하여 규칙적으로 extendedArray에 원소를 넣고 비교하여 score 값을 증가시킨다.
마지막으로 score1, score2, score3의 값과 세 점수의 최댓값을 비교한다.
정답으로 반환한 배열에 최댓값과 일치하는 값의 번호만 넣어준다.
728x90