본문 바로가기

Programming

[Algorithm] 프로그래머스 - level1 <모의고사>

<문제소개>

  • 문제명 : 모의고사
  • 사이트 : 프로그래머스
  • 난이도 : level 1
  • 사용 언어 : javascript

<문제 풀이>

접근 방식

1. 학생 각각이 찍을 답을 패턴화한다

2. 학생의 답과 주어진 답을 비교하여 점수를 구한다.

3. 점수가 가장 높은 학생을 배열에 담아 반환한다.


<내 코드>

function solution(answers) {
  const result = [];
  const answersCount = answers.length;
  
  const firstAnswers = [1, 2, 3, 4, 5];
  const secondAnswers = [2, 1, 2, 3, 2, 4, 2, 5];
  const thirdAnswers = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5];

  const firstGrade = answers.filter((a, i) => a === firstAnswers[i % firstAnswers.length]).length;
  const secondGrade = answers.filter((a, i) => a === secondAnswers[i % secondAnswers.length]).length;
  const thirdGrade = answers.filter((a, i) => a === thirdAnswers[i % thirdAnswers.length]).length;
  
  const maxGrade = Math.max(firstGrade, secondGrade, thirdGrade);
  
  if (firstGrade === maxGrade) result.push(1); 
  if (secondGrade === maxGrade) result.push(2);
  if (thirdGrade === maxGrade) result.push(3);

  return result;
}

 


<보완할 점>

filter메소드 : 배열에서 함수를 통과한 원소만을 담은 새로운 배열을 생성한다.

[array].filter(function(item, index, array) { ... }, thisArg);

const correct = [1, 2, 3, 4, 5]; // 정답
const student = [3, 2, 4, 4, 5]; // 학생의 답

// 정답과 학생의 답이 일치하는 답만을 담은 배열 생성
const result = correctAnswers.filter((n, i) => n === studenct(i)) // [2, 4, 5]

// 정답의 개수(점수)
result.length; // 3