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

2023. 5. 4. 16:49·Coding Test/Programmers_JavaScript
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
저작자표시 비영리 변경금지 (새창열림)

'Coding Test > Programmers_JavaScript' 카테고리의 다른 글

[JavaScript/프로그래머스] 연습문제 - 덧칠하기  (0) 2023.05.09
[JavaScript/프로그래머스] 연습문제 - 기사단원의 무기  (0) 2023.05.09
[JavaScript/프로그래머스] 연습문제 - 카드 뭉치  (0) 2023.05.08
[JavaScript/프로그래머스] 연습문제 - 최댓값과 최솟값  (0) 2023.05.08
[JavaScript/프로그래머스] Dev-Matching: 웹 백엔드 개발자(상반기) - 로또의 최고 순위와 최저 순위  (0) 2023.05.08
'Coding Test/Programmers_JavaScript' 카테고리의 다른 글
  • [JavaScript/프로그래머스] 연습문제 - 기사단원의 무기
  • [JavaScript/프로그래머스] 연습문제 - 카드 뭉치
  • [JavaScript/프로그래머스] 연습문제 - 최댓값과 최솟값
  • [JavaScript/프로그래머스] Dev-Matching: 웹 백엔드 개발자(상반기) - 로또의 최고 순위와 최저 순위
ThreeLight
ThreeLight
ThreeLight Studio의 블로그, TimeMap.exe에 오신 것을 환영합니다.
  • ThreeLight
    TimeMap.exe
    ThreeLight
  • 전체
    오늘
    어제
    • 분류 전체보기 (245)
      • Checkpoint (1)
      • (3D)Dev Deep Dive (0)
        • Templates & Guides (9)
        • Frontend origin (9)
        • Backend origin (1)
        • TroubleShootings (4)
      • Development Study (95)
        • Frontend (36)
        • Backend (21)
        • CS(Computer Science) (2)
        • Background Knowledges (11)
        • Algorithm (2)
        • Mobile (3)
        • AWS (6)
        • Python (6)
        • MSW(MapleStoryWorlds) (8)
      • Coding Test (59)
        • 문제.zip (1)
        • BaekJoon_JavaScript (0)
        • Programmers_JavaScript (9)
        • BaekJoon_Python (23)
        • Programmers_Python (10)
        • Undefined_Python (3)
        • Programmers_SQL (13)
      • 활동내역.zip (43)
        • 개인 (21)
        • Techeer (12)
        • Bootcamp (7)
        • Hackathon (1)
        • TeamProjects (2)
      • 여기 괜찮네??(사이트 | App) (5)
      • 재미있는 주제들 (8)
      • 개발 외 공부 저장소 (11)
        • 생산운영관리 (3)
        • 생활속의금융 (6)
        • 경영정보시스템 (2)
  • 링크

    • TimeMap.dmg (Portfolio)
    • GitHub 바로가기
    • 오픈프로필(카카오톡)
    • Medium 바로가기
    • Disquiet 바로가기
    • LinkedIn 바로가기
  • 인기 글

  • 태그

    프로그래머스
    HTML
    CSS
    react
    programmers
    Python
    Baek Joon
    SQL
    TypeScript
    JavaScript
  • 최근 글

  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.1
ThreeLight
[JavaScript/프로그래머스] 연습문제 - 명예의 전당 (1)
상단으로

티스토리툴바