Skip to content

Conversation

@uyeon0
Copy link
Collaborator

@uyeon0 uyeon0 commented Oct 7, 2025

User description

오늘도 멋져요 👍✨


PR Type

Enhancement


Description

  • 프로그래머스 메뉴 리뉴얼 문제 - 조합 알고리즘 구현

  • 프로그래머스 의상 문제 - Map을 활용한 해시 구현

  • 프로그래머스 압축 문제 - LZW 압축 알고리즘 구현

  • README.md 포맷팅 및 링크 업데이트 작업


@uyeon0 uyeon0 added the programmers Programmers 문제 풀이 label Oct 7, 2025
@github-actions
Copy link

github-actions bot commented Oct 7, 2025

PR Reviewer Guide 🔍

🧪 PR contains tests
⚡ Recommended focus areas for review

성능 개선 가능성

combination 함수에서 재귀 호출과 배열 복사로 인한 O(2^n) 시간 복잡도. 반복문 기반 조합 생성이나 비트마스킹을 사용하여 성능 개선 가능.

function combination(arr, n) {
  // arr 배열에서 n개 뽑는 조합들을 담은 배열 반환
  if (n === 1) return arr.map((el) => [el]);

  const result = [];
  arr.forEach((fixed, idx) => {
    // fixed 이후의 원소들을 뽑는 조합을 찾아내야 함.
    const rest = arr.slice(idx + 1);
    const comb = combination(rest, n - 1);
    const combine = comb.map((c) => [fixed, ...c]);
    result.push(...combine);
  });

  return result;
}
메모리 최적화

문자열 슬라이싱 연산이 반복적으로 발생하여 메모리 사용량이 증가할 수 있음. 투 포인터 방식으로 변경하여 메모리 사용량 최적화 가능.

while (cursor < msg.length) {
  // 2. 사전에서 현재 입력과 일치하는 가장 긴 문자열 w 찾기
  let offset = 1;
  while (
    cursor + offset <= msg.length &&
    dict.has(msg.slice(cursor, cursor + offset))
  ) {
    offset++;
  }
  const w = msg.slice(cursor, cursor + offset - 1);
  // 3. w에 해당하는 사전의 색인 번호 출력
  answer.push(dict.get(w));
  // 4. 입력에서 처리되지 않은 다음 글자가 남아 있다면 (c) w+c에 해당하는 단어를 사전에 등록한다. (인덱스는 사전의 가장 마지막 인덱스)
  if (cursor + offset - 1 < msg.length) {
    const c = msg[cursor + offset - 1];
    dict.set(w + c, dict.size + 1);
  }
  // 5. 입력에서 w 제거
  cursor = cursor + offset - 1;
}
엣지 케이스

의상 종류가 하나만 있는 경우나 모든 의상 종류에 하나의 의상만 있는 경우에 대한 처리가 필요할 수 있음. 입력 데이터 유효성 검사 추가 권장.

function solution(clothes) {
  const closet = new Map(); // key: 의상의 종류, value: 의상 이름이 담긴 배열;
  for (const cloth of clothes) {
    const [name, type] = cloth;
    if (closet.has(type)) {
      closet.get(type).push(name);
    } else {
      closet.set(type, [name]);
    }
  }

  // 해당 타입을 안입는 경우까지 포함한 조합의 경우의 수 구함 - 아무것도 입지 않는 경우의 수 빼기
  const answer =
    [...closet.values()].reduce((acc, cur) => acc * (cur.length + 1), 1) - 1;
  return answer;
}

@github-actions
Copy link

github-actions bot commented Oct 7, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
메모이제이션으로 성능 최적화

combination 함수를 메모이제이션을 활용하여 최적화하세요. 동일한 입력에 대한 중복 계산을 피하고 성능을 향상시킬 수 있습니다.

Programmers/Level2/72411_메뉴_리뉴얼.js [9-23]

-function combination(arr, n) {
-  // arr 배열에서 n개 뽑는 조합들을 담은 배열 반환
-  if (n === 1) return arr.map((el) => [el]);
+const memoizedCombination = (() => {
+  const memo = new Map();
+  
+  return function combination(arr, n) {
+    const key = `${arr.join('')}-${n}`;
+    if (memo.has(key)) return memo.get(key);
+    if (n === 1) return arr.map((el) => [el]);
 
-  const result = [];
-  arr.forEach((fixed, idx) => {
-    // fixed 이후의 원소들을 뽑는 조합을 찾아내야 함.
-    const rest = arr.slice(idx + 1);
-    const comb = combination(rest, n - 1);
-    const combine = comb.map((c) => [fixed, ...c]);
-    result.push(...combine);
-  });
+    const result = [];
+    arr.forEach((fixed, idx) => {
+      const rest = arr.slice(idx + 1);
+      const comb = combination(rest, n - 1);
+      const combine = comb.map((c) => [fixed, ...c]);
+      result.push(...combine);
+    });
 
-  return result;
-}
+    memo.set(key, result);
+    return result;
+  }
+})();
Suggestion importance[1-10]: 7

__

Why: 메모이제이션을 통해 중복 계산을 피하고 성능을 향상시킬 수 있는 유효한 제안입니다. 특히 재귀 함수에서 동일한 입력에 대한 계산이 반복될 수 있는 combination 함수에서 효과적입니다.

Medium
함수형 스타일로 코드 개선

Mapset 메서드 대신 배열 메서드를 활용하여 더 간결하고 가독성 있는 코드로 리팩토링하세요. reduce 메서드를 사용하면 코드를 더 함수형
스타일로 작성할 수 있습니다.

Programmers/Level2/42578_의상.js [9-17]

-const closet = new Map(); // key: 의상의 종류, value: 의상 이름이 담긴 배열;
-for (const cloth of clothes) {
-  const [name, type] = cloth;
-  if (closet.has(type)) {
-    closet.get(type).push(name);
-  } else {
-    closet.set(type, [name]);
-  }
-}
+const closet = clothes.reduce((acc, [name, type]) => {
+  acc.set(type, [...(acc.get(type) || []), name]);
+  return acc;
+}, new Map());
Suggestion importance[1-10]: 6

__

Why: reduce 메서드를 사용한 함수형 접근은 코드를 더 간결하게 만들어주며, 반복문과 조건문을 제거하여 가독성을 향상시킵니다. 하지만 현재 구현도 명확하고 이해하기 쉽습니다.

Low
함수 분리로 가독성 개선

사전 초기화 로직을 별도의 함수로 분리하여 코드의 가독성과 재사용성을 높이세요. 상수 값들도 의미있는 이름으로 분리하면 좋습니다.

Programmers/Level2/17684_[3차]_압축.js [11-15]

-const dict = new Map();
-const CAPITAL_A = 65;
-for (let i = 0; i < 26; i++) {
-  dict.set(String.fromCharCode(CAPITAL_A + i), i + 1);
+const ALPHABET_SIZE = 26;
+const CAPITAL_A_CODE = 65;
+
+function initializeDictionary() {
+  const dict = new Map();
+  for (let i = 0; i < ALPHABET_SIZE; i++) {
+    dict.set(String.fromCharCode(CAPITAL_A_CODE + i), i + 1);
+  }
+  return dict;
 }
 
+const dict = initializeDictionary();
+
Suggestion importance[1-10]: 5

__

Why: 사전 초기화 로직을 별도 함수로 분리하고 상수를 명확히 정의하는 것은 코드 구조를 개선하는 적절한 제안이지만, 현재 코드도 충분히 이해하기 쉽고 간단합니다.

Low
테이블 헤더 포맷 정리

테이블 헤더 행의 열 너비를 일관되게 정렬하고 불필요한 공백을 제거하여 가독성을 개선하세요. 각 열의 내용에 맞게 최소한의 너비만 사용하는 것이
좋습니다.

Programmers/README.md [9-10]

-| 문제 번호 | 문제 이름                                               | 풀이 코드                                                                                                                                     | 문제 링크                                                              |
-| --------- | ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
+| 문제 번호 | 문제 이름 | 풀이 코드 | 문제 링크 |
+|-----------|-----------|-----------|-----------|
Suggestion importance[1-10]: 3

__

Why: 테이블 헤더의 불필요한 공백 제거는 가독성을 약간 개선할 수 있지만, 현재 포맷도 충분히 읽기 쉽고 기능적으로 문제가 없어 중요도가 낮습니다.

Low

@yoouyeon yoouyeon added the ready-to-merge pr을 머지해주세요 label Oct 8, 2025
@uyeon0 uyeon0 merged commit 9d88749 into main Oct 8, 2025
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

programmers Programmers 문제 풀이 ready-to-merge pr을 머지해주세요

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants