티스토리 뷰

알고리즘/프로그래머스 문제풀이

프로그래머스 NodeJS Level 1 : 모의고사

YG - 96년생 , 강아지 있음, 개발자 희망 2022. 3. 16. 12:00
/* get input */
const answers = [1, 2, 3, 4, 5];
/* get input end */

/* solve */

function solution(answers) {
  var answer = [];
  let first = [];
  let second = [];
  let third = [];
  let firstCollect = 0;
  let secondCollect = 0;
  let thirdCollect = 0;

  while (first.length < 10001) {
    first.push(...[1, 2, 3, 4, 5]);
  }
  while (second.length < 10001) {
    second.push(...[2, 1, 2, 3, 2, 4, 2, 5]);
  }
  while (third.length < 10001) {
    third.push(...[3, 3, 1, 1, 2, 2, 4, 4, 5, 5]);
  }
  for (let i = 0; i < answers.length; i++) {
    first.push(1, 2, 3, 4, 5);
  }

  for (let i = 0; i < answers.length; i++) {
    if (first[i] === answers[i]) {
      firstCollect++;
    }
    if (second[i] === answers[i]) {
      secondCollect++;
    }
    if (third[i] === answers[i]) {
      thirdCollect++;
    }
  }
  const max = Math.max(firstCollect, secondCollect, thirdCollect);

  if (max === firstCollect) answer.push(1);
  if (max === secondCollect) answer.push(2);
  if (max === thirdCollect) answer.push(3);

  answer.sort();
  return answer;
}
/* solve end */

/* print output */
console.log(solution(answers));
/* print output end */

while문으로 먼저 테스트 개수인 10000개를 배열로 만들어서 풀었습니다.

 

다른 사람들 풀이에서는 10000개가 아니라 lenght로 반복조건을 만들어서 푸는 방법을 보았는데 좋아 보였습니다.

 

그리고 저는 각각 answer.length 만큼 for문을 돌려서 정답이 가장 많이 맞은 사람들을 answer에 넣어주었고 sort로 여러사람이 정답이 같을경우에 정렬해주었습니다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함