처음부터 차근차근

[프로그래머스] Lv2 의상 본문

코딩테스트/Javascript

[프로그래머스] Lv2 의상

HangJu_95 2023. 11. 1. 16:52
728x90

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/12951

문제 설명

내 풀이

function solution(clothes) {
    // 의상의 종류를 key, 그것에 일치하는 의상의 개수를 hash라고 한다.
    let key = [];
    let hash = [];
    let answer = 1;
    // 반복문을 돌려 hash table을 생성하자.
    for(let i = 0; i < clothes.length; i++) {
        if (key.indexOf(clothes[i][1]) == -1) {
            key.push(clothes[i][1]);
            hash.push(1);
        } else {
            hash[key.indexOf(clothes[i][1])]++;
        }
    }
    for (let value of hash) {
        answer *= (value + 1)
    }
    return answer -1
}

 

종류에 따른 의상 구분을 할 경우 hash 자료구조를 사용

이후, 종류별로 구분이 되었다면 조합할 수 있는 개수를 계산하는데, 이는 다른 사람의 풀이 법을 참고하면, 굉장히 간단한 코드이다.

https://school.programmers.co.kr/questions/56645

다른 사람의 풀이

function solution(clothes) {
    return Object.values(clothes.reduce((obj, t)=> {
        obj[t[1]] = obj[t[1]] ? obj[t[1]] + 1 : 1;
        return obj;
    } , {})).reduce((a,b)=> a*(b+1), 1)-1;    
}

나와 다르게 객체로 hash를 만든 케이스. reduce를 사용하여 코드를 깔끔하게 풀었다.

오늘 배운 점

  • hash를 사용하는 문제 풀이법.
  • 알고리즘 하나 더 알아간다.