Coding Test/Programmers_JavaScript

[JavaScript/프로그래머스] 연습문제 - 명예의 전당 (1)

  • -
728x90

문제 링크

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


초기 정답 코드

function solution(k, score) {
  let lowList = [];
  let nowList = [];
  for (let i = 0; i < score.length; i++) {
    if (nowList.length < k) {
      nowList.push(score[i]);
      lowList.push(nowList.reduce((a, b) => Math.min(a, b)));
      nowList.sort((a, b) => a - b);
    } else {
      if (score[i] > nowList.reduce((a, b) => Math.min(a, b))) {
        nowList.splice(0, 1);
        nowList.push(score[i]);
      }
      lowList.push(nowList.reduce((a, b) => Math.min(a, b)));
      nowList.sort((a, b) => a - b);
    }
  }
  return lowList;
}

변수 설명
- 명예의 전당에 올라가있는 점수의 개수 k
- 전체 회차가 진행되면서 얻었던 점수를 모아두는 배열 score
- 결과를 반환할 배열 lowList
- 현재 들어있는 점수를 나타내는 배열 nowList

 

로직 설명
for 루프를 사용하여 score 배열의 각 요소에 대해 다음 작업을 수행합니다

  • if(nowList.length<k) 조건문을 사용하여 nowList 배열에 score[i] 요소를 추가합니다
    • 이때 nowList 배열에 추가된 요소들 중 최소값을 찾아 lowList 배열에 추가합니다.
    • 이를 위해 Array.reduce() 메소드와 Math.min() 함수를 사용합니다.
  • else 조건문에서는, nowList 배열에 k개의 요소가 모두 채워져 있는 경우입니다.
    • 이때 score[i]가 nowList 배열에 있는 요소들 중 최소값보다 크다면, nowList 배열에서 최소값을 제거하고 score[i]를 추가합니다.
    • 이후, nowList 배열에 있는 요소들 중 최소값을 찾아 lowList 배열에 추가합니다.

lowList 배열을 반환합니다.


하지만 여기서 그치지 않고 코드를 더 나은 방향으로 개선해보기로 했습니다.


1차 개선 - 코드 길이 줄이기 (Math.min 메서드 사용)

nowList.reduce((a, b) => Math.min(a, b))

==> Math.min(...nowList) 로 변경

둘이 같은 의미를 가지고 있지만 전개 연산자(...arr) 를 이용하여 코드의 길이를 대폭 줄였습니다.

function solution(k, score) {
  let lowList = [];
  let nowList = [];
  for (let i = 0; i < score.length; i++) {
    if (nowList.length < k) {
      nowList.push(score[i]);
      lowList.push(Math.min(...nowList));
      nowList.sort((a, b) => a - b);
    } else {
      if (score[i] > Math.min(...nowList)) {
        nowList.splice(0, 1);
        nowList.push(score[i]);
      }
      lowList.push(Math.min(...nowList));
      nowList.sort((a, b) => a - b);
    }
  }
  return lowList;
}

2차 개선 - 코드 길이 줄이기 (치환)

같은 역할을 하는 변수를 이용해서 더 짧은 코드로 만들었습니다.

function solution(k, score) {
    let lowList = [];
    let nowList = [];
    for(let i=0; i<score.length; i++){
        if(i<k){ // if(nowList.length<k)
            nowList.push(score[i]);
            lowList.push(Math.min(...nowList));
            nowList.sort((a, b) => a - b);
        } else {
            if(score[i] > Math.min(...nowList)){
                nowList.splice(0, 1);
                nowList.push(score[i]);
            }
            lowList.push(Math.min(...nowList));
            nowList.sort((a, b) => a - b);
        }
    }
    return lowList;
}

3차 개선 - 코드 길이 줄이기 (Array 개선)

Array.forEach() 사용을 통해 for 문 조건 부분의 코드 길이를 줄이고

Array.splice() 대신 Array.shift()를 사용하여 배열 부분의 코드를 개선하였습니다.

function solution(k, score) {
  let lowList = [];
  let nowList = [];
  score.forEach((s) => {
    if (nowList.length < k) {
      nowList.push(s);
      lowList.push(Math.min(...nowList));
      nowList.sort((a, b) => a - b);
    } else {
      if (s > Math.min(...nowList)) {
        nowList.shift();
        nowList.push(s);
      }
      lowList.push(Math.min(...nowList));
      nowList.sort((a, b) => a - b);
    }
  });
  return lowList;
}

End

728x90
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.