[프로그래머스] 의상

이찬혁·2024년 4월 12일

알고리즘

목록 보기
41/72

프로그래머스 Lv2 - 의상 문제

프로그래머스 알고리즘 고득점 Kit 카테고리의 해시 문제 중 레벨 2 의상 목록 문제를 풀이했다.

  1. 이중 for문을 통해 해시맵에 키: 의상 종류, 값: 종류별 의상 갯수를 업데이트
  2. 정리된 해시맵에서 for문을 통해 경우의 수 업데이트
    answer *= (entry.getValue() + 1); 중 +1을 하는 이유는 의상 종류를 안 입는 경우를 추가해준 것
    마지막 answer - 1을 하는 이유는 전부다 안 입는 경우는 없기 때문에 감소해준 것

Clothes.java

package com.example.Programmers.Lv2;

import java.util.HashMap;
import java.util.Map;

public class Clothes {
    public int solution(String[][] clothes) {
        int answer = 1;
        HashMap<String, Integer> map = new HashMap<>();

        for (int i = 0; i < clothes.length; i++) {
            int clothesTypeIdx = clothes[i].length - 1;
            for (int j = 0; j < clothesTypeIdx; j++) {
                String clothesType = clothes[i][clothesTypeIdx];
                if (!map.containsKey(clothesType)) {
                    map.put(clothesType, 0);
                }
                map.replace(clothesType, map.get(clothesType) + 1);
            }
        }

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            answer *= (entry.getValue() + 1);
        }

        return answer - 1;
    }
}

ClothesTest.java

package com.example.Programmers.Lv2;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class ClothesTest {
    @Test
    public void testClothes() {
        Clothes c = new Clothes();

        int result1 = c.solution(new String[][] { { "yellow_hat", "headgear" }, { "blue_sunglasses", "eyewear" },
                { "green_turban", "headgear" } });
        int result2 = c.solution(
                new String[][] { { "crow_mask", "face" }, { "blue_sunglasses", "face" }, { "smoky_makeup", "face" } });

        assertEquals(5, result1);
        assertEquals(3, result2);

    }
}
profile
나의 개발로그

0개의 댓글