본문 바로가기

프로그래머스

[프로그래머스 Level 2] 위장 [Java]

 

 


https://school.programmers.co.kr/learn/courses/30/lessons/42578/solution_groups?language=java 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

※. 같은 이름의 의상은 없다.

(옷의 이름은 저장하지 않아도 된다.)

 

※. 종류(clothes[n][1])의 문자열이 몇 번 나왔는지 확인하는 map(중복)을 생성한다.(경우의 수)

 

※. map을 탐색한다.

https://wakestand.tistory.com/247

 

자바 Iterator 개념부터 사용 방법까지

자바에서 Iterator는 컬렉션 프레임워크(Collection Framework)에서 값을 가져오거나 삭제할 때 사용하는데 먼저 컬렉션 프레임워크는 List, Set, Map, Queue 등을 말한다 다음으로 컬렉션 프레임워크를 생성

wakestand.tistory.com

 

※. 옷을 안입는 경우를 추가해주어 계산한다.

(map의 value에 +1을 해준다.)

 

※. 최소 한 개의 옷은 입기 때문에 모두 안입는 경우를 빼준다.

 


import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Iterator;
class Solution {
    public int solution(String[][] clothes) {
        int answer = 1;
		HashMap<String, Integer> hashmap = new HashMap<>();
		
        for(int i = 0; i < clothes.length; i++) {
        	hashmap.put(clothes[i][1], hashmap.getOrDefault(clothes[i][1], 0)+1);
        }
        
        Iterator<Integer> it = hashmap.values().iterator();
        while(it.hasNext()) {
        	answer *= it.next()+1;
        }
        
        return answer-1;
	}
}

 


※. 스트림 생성(배열) Arrays.stream()

※. 요소들을 특정조건에 해당하는 값으로 변경 map()

※. 중복 제거 distinct()

※. map(type -> Arrays.stream(clothes).filter(c -> c[1].equals(type)).count())

(중복 제거된 종류의 갯수를 카운트함, count는 long타입을 반환하기 때문에 int로 형변환)

※. 옷을 안입는 경우 1을 추가

※. 스트림의 요소들을 하나로 만들어줌 reduce

 


import java.util.*;
import java.util.stream.*;
class Solution {
    public int solution(String[][] clothes) {
        return Arrays.stream(clothes)
            .map(c -> c[1])
            .distinct()
            .map(type -> (int)Arrays.stream(clothes).filter(c -> c[1].equals(type)).count())
            .map(c -> c + 1)
            .reduce(1, (c, n) -> c * n) - 1;
    }
}