알고리즘/프로그래머스 문제풀이

[프로그래머스] 위장 java / HashMap 사용

자바칩 프라푸치노 2021. 6. 1. 10:28

 

처음에는 해시맵에 넣어서~~ 명칭으로 맵으로 만드는 방법도 헤매고~~ 그랬지만

이렇게 간단하게 풀 수 있었다.;;

import java.util.HashMap;
import java.util.Iterator;

class Solution {
    public int solution(String[][] clothes) {
     int answer = 1;
	        
	        HashMap<String, Integer> clothesmap = new HashMap<String, Integer>();
	        
	        for (int i = 0; i < clothes.length; i++) {
	        	String key = clothes[i][1];
				if (!clothesmap.containsKey(key)) {
					clothesmap.put(key, 1);
				}
				else {
					clothesmap.put(key, clothesmap.get(key)+1);
				}
			}
	        
	        Iterator<Integer> iter = clothesmap.values().iterator();
	        while(iter.hasNext()) {
	        	answer *= iter.next().intValue()+1;
	        }
	        return answer-1;
    }
}

answer은 곱하기를 위해 1로 설정.

경우의 수로 해야하니까 일단 clothes[i][1]에 있는 옷의 종류와 그 종류에 맞는 옷의 개수로 map을 만들어야한다.

그래서 HashMap은 String과 Integer로 정의해주었고

map에 옷의 종류로 들어가있는 값이 없으면 value는 1을 넣어주고

있으면 그 value에 +1을 해주면 된다.

그리고 iterator을 사용하여 

값들을 +1한 값을 다 곱해주었다.

왜 +1한 값을 곱해주냐하면

만약에 상의 3 하의 3 선글 2 신발2가 있다 치면

만약에 하나씩 꼭 입어야하면 3*3*2*2 가 되겠지만

꼭 하나씩 입지 않아도 되니까

1번 상의를 입는 경우, 2번 상의를 입는 경우, 3번 상의를 입는 경우, 안입는 경우 이렇게 해서 4,

하의도 마찬가지로 4

선글도 마찬가지로 3

신발도 마찬가지로3

이렇게 해서 4*4*3*3 이 되겠다.

그런데 모두 다 안입는 경우가 있을 수 있으니 마지막에 -1을 해준다. 

 

 


다른 사람의 풀이

import java.util.*;
import static java.util.stream.Collectors.*;

class Solution {
    public int solution(String[][] clothes) {
        return Arrays.stream(clothes)
                .collect(groupingBy(p -> p[1], mapping(p -> p[0], counting())))
                .values()
                .stream()
                .collect(reducing(1L, (x, y) -> x * (y + 1))).intValue() - 1;
    }
}

이거는 처음 보는 코드이다. 

정말 고수다!

 

728x90