모의고사

Posted by Casval's Storage on October 30, 2020

모의고사

단순히 모두 비교하여 결과를 도출하는 문제.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function solution(answers) {
  var answer = [];
  
  const one = [1,2,3,4,5];
  const two = [2,1,2,3,2,4,2,5];
  const three = [3,3,1,1,2,2,4,4,5,5];
  
  one.cnt = two.cnt = three.cnt = 0;
  
  answers.forEach((a, i) => {
      if (one[i%one.length] === a) {
          one.cnt++; 
      }
      if (two[i%two.length] === a) {
          two.cnt++; 
      }
      if (three[i%three.length] === a) {
          three.cnt++;
      }
  });
  
  const arr = [one.cnt, two.cnt, three.cnt];
  const max = Math.max(...arr);
  arr.forEach((v, i) => {
      if (v === max) {
          answer.push(i + 1);
      }
  })
  
  
  return answer;
}

console.log(solution([1,2,3,4,5]))
console.log(solution([1,3,2,4,2]))

체크포인트

Math.max() 함수는 그냥 배열을 넣으면 안되고 spread operator를 함께 넣어야 배열의 최대값을 반환해 준다.

(출처: programmers)