const firstStudent = (arr) => {
let count = 0;
arr.forEach((num, idx) => {
const standard = (idx % 5) + 1;
switch (standard) {
case 1:
if (num == 1) {
count++;
}
break;
case 2:
if (num == 2) {
count++;
}
break;
case 3:
if (num == 3) {
count++;
}
break;
case 4:
if (num == 4) {
count++;
}
break;
case 5:
if (num == 5) {
count++;
}
break;
}
});
return count;
};
const secondStudent = (arr) => {
let count = 0;
arr.forEach((num, idx) => {
const isIndexOdd = (idx + 1) % 2;
if (isIndexOdd) {
if (num == 2) {
count++;
return;
// forEach문에서 continue를 사용할 수 있는 방법을 찾아보니
// return으로 빠져나오면 되는 것이었다.
// 그런데 생각해보니 어차피 이 뒤로 실행할 문장이 따로 없어서 return문이 있으나마나...
}
} else {
const standard = (Math.floor(idx / 2) % 4) + 1;
switch (standard) {
case 1: {
if (num == 1) {
count++;
}
break;
}
case 2: {
if (num == 3) {
count++;
}
break;
}
case 3: {
if (num == 4) {
count++;
}
break;
}
case 4: {
if (num == 5) {
count++;
}
break;
}
}
}
});
return count;
};
const thirdStudent = (arr) => {
let count = 0;
arr.forEach((num, idx) => {
const standard = (Math.floor(idx / 2) % 5) + 1;
switch (standard) {
case 1: {
if (num == 3) {
count++;
}
break;
}
case 2: {
if (num == 1) {
count++;
}
break;
}
case 3: {
if (num == 2) {
count++;
}
break;
}
case 4: {
if (num == 4) {
count++;
}
break;
}
case 5: {
if (num == 5) {
count++;
}
break;
}
}
});
return count;
};
const solution = (answers) => {
const result = [];
const hashTable = {
1: firstStudent(answers),
2: secondStudent(answers),
3: thirdStudent(answers),
};
const max = Math.max(...Object.values(hashTable));
for (let key in hashTable) {
if (hashTable[key] == max) {
result.push(parseInt(key));
}
}
return result;
};
const answers = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5];
완전탐색이니 단순 노가다 문제겠지 하고 만만하게 봤다가 예외처리가 틀려서 생각보다 한참이나 걸렸다
좋아요를 가장 많이 받은 사람의 풀이를 보니 너무 허탈해졌다
(왜 클린 코드에서 조건문을 최대한 쓰지 말라는지도 대강 알겠다)
(조건문 범벅인 내 풀이가 저만큼 간결해질 수 있으니...)
function solution(answers) {
const answer = [];
const first = [1, 2, 3, 4, 5];
const second = [2, 1, 2, 3, 2, 4, 2, 5];
const third = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5];
const list = [];
const f = answers.reduce((acc, cur, idx) => {
if (cur == first[idx % first.length]) {
return ++acc;
}
return acc;
}, 0);
list.push(f);
const s = answers.reduce((acc, cur, idx) => {
if (cur == second[idx % second.length]) {
return ++acc;
}
return acc;
}, 0);
list.push(s);
const t = answers.reduce((acc, cur, idx) => {
if (cur == third[idx % third.length]) {
acc++;
}
return acc;
}, 0);
list.push(t);
const max = Math.max(...list);
list.forEach((count, idx) => {
if (count == max) {
answer.push(idx + 1);
}
});
return answer;
}