ㅁㄴㅇㄻㄴㅇㄹ

[코딩테스트] 프로그래머스 위장 with javascript 본문

코딩테스트

[코딩테스트] 프로그래머스 위장 with javascript

hanbin8269 2021. 5. 6. 10:32

문제 풀이 코드

function solution(clothes) {
    var answer = 1;
    var clothesDict = {}
    for (var i = 0; i < clothes.length; i++){ 
        if (clothes[i][1] in clothesDict){  // #1
            clothesDict[clothes[i][1]] += 1;
        }else{
            clothesDict[clothes[i][1]] = 1;
        }
    }
    for (var key in clothesDict){  // #2
        answer *= clothesDict[key] + 1
    }
    return answer - 1;  // #3
}

#1

만약 clothesDict 에 없는 key 값이 들어왔다면 1로 초기화 시키고, 존재한다면 1 을 더해줘 해당 의상 종류가 몇개가 있는지 저장합니다.

#2

의상 갯수 + 입지 않았을 때의 경우를 clothesDict[key] + 1로 표현했다.

#3

아무것도 입지 않았을 경우를 제외하기 위해 1을 빼주었다.