programmers - 모의고사 with JS

@p-iknow 🎹 · September 02, 2019

Problem
What I learned
Solve
내 풀이
다른 사람 풀이
enumerate
참고

Problem

image

What I learned

나머지 연산자의 활용

const getScore = (answers, supo) => {
  let score = 0;
  let supoLength = supo.length;
  answers.forEach((answer, i) => {
    // 나머지 연산자를 통해 패턴과 답의 일치를 점검
    if (answer === supo[i % supoLength]) score += 1;
  });
  return score;
};

오름차순 정렬

미리 수포자 1, 2, 3 정렬한 배열에 forEach 를 적용해 max값과 일치하면 push 하도록 하여 오름차순 정렬 구현

scores.forEach((score, i) => {
  if (score === max) answer.push(i + 1);
});

Solve

내 풀이

const supo1 = [1, 2, 3, 4, 5];
const supo2 = [2, 1, 2, 3, 2, 4, 2, 5];
const supo3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5];
const supos = [supo1, supo2, supo3];

const getScore = (answers, supo) => {
  let score = 0;
  let supoLength = supo.length;
  answers.forEach((answer, i) => {
    if (answer === supo[i % supoLength]) score += 1;
  });
  return score;
};

function solution(answers) {
  const scores = supos.map(supo => {
    return getScore(answers, supo);
  });
  const max = Math.max(...scores);
  const answer = [];
  scores.forEach((score, i) => {
    if (score === max) answer.push(i + 1);
  });

  return answer;
}

다른 사람 풀이

def solution(answers):
    pattern1 = [1,2,3,4,5]
    pattern2 = [2,1,2,3,2,4,2,5]
    pattern3 = [3,3,1,1,2,2,4,4,5,5]
    score = [0, 0, 0]
    result = []

    for idx, answer in enumerate(answers):
        if answer == pattern1[idx%len(pattern1)]:
            score[0] += 1
        if answer == pattern2[idx%len(pattern2)]:
            score[1] += 1
        if answer == pattern3[idx%len(pattern3)]:
            score[2] += 1

    for idx, s in enumerate(score):
        if s == max(score):
            result.append(idx+1)

    return result

enumerate

  • 반복문 사용 시 몇 번째 반복문인지 확인이 필요할 수 있다.
  • 인덱스 번호와 컬렉션의 원소를 tuple형태로 반환한다.
>>> t = [1, 5, 7, 33, 39, 52]
>>> for p in enumerate(t):
...     print(p)
...
(0, 1)
(1, 5)
(2, 7)
(3, 33)
(4, 39)
(5, 52)
  • tuple형태 반환을 이용하여 아래처럼 활용할 수 있다.
>>> for i, v in enumerate(t):
...     print("index : {}, value: {}".format(i,v))
...
index : 0, value: 1
index : 1, value: 5
index : 2, value: 7
index : 3, value: 33
index : 4, value: 39
index : 5, value: 52

참고

@p-iknow 🎹
많은 것을 이해하고 싶습니다. 더 이해하기 위해 노력합니다.