[프로그래머스] 위장

yeong·2022년 6월 14일
0

문제:
https://programmers.co.kr/learn/courses/30/lessons/42883?language=javascript
카테고리 : 해시

문제 접근 :

주어진 의상 정보에서 서로 다른 옷의 조합의 수를 세는 문제이다.
경우의 수로 생각하면 단순한 문제이다.
옷의 종류별로 동시에 발생할 수 있는 옷의 모든 경우의수를 구하면 된다.

문제 풀이

  1. 우선 옷의 종류별 의상의 갯수를 구한다. 예를들어 input 옷의 정보가 [["yellowhat", "headgear"], ["bluesunglasses", "eyewear"], ["green_turban", "headgear"]] 라면, headgear가 2가지, eyewear가 1가지인 조합이다.
    그리고 각각의 옷의 종류를 아예 안입는 경우의 수를 각각+1 한다.
  2. 옷의 종류별로 일어날 수 있는 경우의 수를 곱한다. total = headgear*eyewear...
  3. 모든 경우의수를 구하고 아무것도 안입는 1가지 경우의 수를 제외한다
    total-=1;

코드

function solution(clothes) {
  var answer =0;
  let lookup = {};
 
  for (let [clothe, kind] of clothes) {
    if (!lookup[kind]) lookup[kind] = [];
    lookup[kind].push(clothe);
  }
  let total = 1;
  for (let kind of Object.keys(lookup)) {
    total *= lookup[kind].length + 1;
  }
  answer = total - 1;
  return answer;
}
profile
안녕하세요!

0개의 댓글