IT/알고리즘 문제 풀이
프로그래머스 코딩연습 - "모의고사" (array, 완전탐색, 기초)
KS짱짱맨
2020. 6. 19. 22:54
모의고사문제 설명
수포자는 수학을 포기한 사람의 준말입니다.
수포자 삼인방은 모의고사에 수학 문제를 전부 찍으려 합니다.
수포자는 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] |
입출력 예 설명
입출력 예 #1
- 수포자 1은 모든 문제를 맞혔습니다.
- 수포자 2는 모든 문제를 틀렸습니다.
- 수포자 3은 모든 문제를 틀렸습니다.
따라서 가장 문제를 많이 맞힌 사람은 수포자 1입니다.
입출력 예 #2
- 모든 사람이 2문제씩을 맞췄습니다.
문제 풀이
function solution(answers) {
var answer = [];
const student1 = [1,2,3,4,5];
const student2 = [2,1,2,3,2,4,2,5];
const student3 = [3,3,1,1,2,2,4,4,5,5];
let score = [0,0,0];
let a = 0;
let b = 0;
let c = 0;
const len = answers.length;
for(let i=0; i<len; i++){
if(answers[i] == student1[i%student1.length]){
a++;
}
if(answers[i] == student2[i%student2.length]){
b++;
}
if(answers[i] == student3[i%student3.length]){
c++;
}
}
if(a > b){
if(b < c){
if(c > a){
answer.push(3);
}else if(c < a){
answer.push(1);
}else{
answer.push(1,3);
}
}else{
answer.push(1);
}
}else if(a < b){
if(b<c){
answer.push(3);
}else if(b>c){
answer.push(2);
}else{
answer.push(2,3);
}
}else{
if(b<c){
answer.push(3);
}else if(b>c){
answer.push(1,2);
}else{
answer.push(1,2,3);
}
}
return answer;
}
Sexy한 풀이) : 프로그래머스 "Vanary" 님의 풀이를 제가 커스터마이징 해보았습니다.
function solution(answers) {
const students = [
[1,2,3,4,5],
[2,1,2,3,2,4,2,5],
[3,3,1,1,2,2,4,4,5,5]
];
let scores = [];
for(let i=0; i<students.length; i++){
scores[i] = {
no: i+1,
score: answers.map((answer, index) => (students[i][index%(students[i].length)] === answer) ? true : false)
.filter( answer => answer).length};
};
const orderedScores = scores.sort( (a,b) => b.score - a.score );
const bestScore = orderedScores.filter( e => e.score === orderedScores[0].score )
.map( e => e.no);
return (bestScore.length > 1) ? bestScore.sort( (a,b) => a - b ) : bestScore
}
와 ㅋㅋㅋ 이건 신세계!!!
728x90