[프로그래머스] 모의고사

skyblue·2023년 3월 9일
0

코딩테스트

목록 보기
1/4

문제 풀이

많은 문제를 맞힌 사람 순서를 구하는 문제다.

https://school.programmers.co.kr/learn/courses/30/lessons/42840

수포자들의 찍는 방식을 배열로 선언하고,
answers 배열에 filter 메서드를 사용하여, 맞힌 수를 구했다.
1번 수포자는 찍는 방식이 1,2,3,4,5,1...로 단순하여, 따로 배열을 선언하지 않고, 수식으로 맞힌 수를 구했다.
if문으로 값의 크기를 비교하여 순서대로 answer 배열에 값을 추가하여 반환했다.

<script>
  function solution(answers) {
      const two = [2, 1, 2, 3, 2, 4, 2, 5];
      const three = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
  
      const a = answers.filter((v, i) => v === i % 5 + 1).length;
      const b = answers.filter((v, i) => v === two[i % 8]).length;
      const c = answers.filter((v, i) => v === three[i % 10]).length;
  
      const answer = [];
      if (a >= b && a >= c) answer.push(1);
      if (b >= a && b >= c) answer.push(2);
      if (c >= b && c >= a) answer.push(3);
  
      return answer;
  }
</script>

다른 분들의 풀이를 보고, 값을 비교하는 부분을 변경했다.

<script>
    const max = Math.max(a,b,c);
    
    if (max === a) answer.push(1);
    if (max === b) answer.push(2);
    if (max === c) answer.push(3);
</script>

변경한 코드가 가독성이 더 좋은 것 같다.

알고리즘

  • 완전 탐색 : 가능한 모든 경우의 수를 다 체크해서 정답을 찾는 방법

0개의 댓글