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

Gaanii·2025년 3월 12일

Problem Solving

목록 보기
180/210
post-thumbnail

아래 프로그래머스 로고를 클릭하면 해당 문제로 이동합니다 😀

프로그래머스로고



풀이과정


노가다를 좋아하는 저는 완전탐색 문제를 제일 좋아한답니다 ? 😂

문제를 읽어보면

  • 1번 수포자 : 1, 2, 3, 4, 5를 반복하며 찍는다.
  • 2번 수포자 : 2, 1, 2, 3, 2, 5, 2, 5, 2를 반복하며 찍는다.
  • 3번 수포자 : 3, 3, 1, 1, 2, 2, 4, 4, 5, 5를 반복하며 찍는다.

이를 우선 배열로 저장해놓고, 매개변수로 주어지는 answers를 돌면서 각 수포자들이 정답을 맞출때마다 점수를 올려주면 된다.

이때, 주의사항 ⚠️
파이썬에서 enumerate, js에서 filter를 쓸 때 idx 값을 사용하게 되는데, 각 수포자들의 번호 찍는 패턴을 저장한 배열의 길이보다 idx가 길어지면 오류가 발생한다.
나머지 연산을 써서 계속 반복을 하게 해주면 쉽게 풀리는 문제였다.

코드


1. Python

def solution(answers):
    result = []
    score = [0, 0, 0]
    person1 = [1, 2, 3, 4, 5]
    person2 = [2, 1, 2, 3, 2, 4, 2, 5]
    person3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]

    for idx, answer in enumerate(answers):
        if answer == person1[idx % len(person1)]:
            score[0] += 1
        if answer == person2[idx % len(person2)]:
            score[1] += 1
        if answer == person3[idx % len(person3)]:
            score[2] += 1
    
    for idx, s in enumerate(score):
        if s == max(score):
            result.append(idx+1)

    return result

2. JS

function solution(answers) {
  var answer = [];
  const p1 = [1, 2, 3, 4, 5];
  const p2 = [2, 1, 2, 3, 2, 4, 2, 5];
  const p3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5];

  let score1 = answers.filter((ans, idx) => ans === p1[idx % p1.length]).length;
  let score2 = answers.filter((ans, idx) => ans === p2[idx % p2.length]).length;
  let score3 = answers.filter((ans, idx) => ans === p3[idx % p3.length]).length;
  const max = Math.max(score1, score2, score3);

  if(score1 === max) answer.push(1);
  if(score2 === max) answer.push(2);
  if(score3 === max) answer.push(3);
    
  return answer;
}


결과


오답이 왜있냐면 ... 제가 p2에 값을 제대로 안넣었거던요 ...
정답

0개의 댓글