문제 설명
1부터 6까지 숫자가 적힌 주사위가 네 개 있습니다. 네 주사위를 굴렸을 때 나온 숫자에 따라 다음과 같은 점수를 얻습니다.


import java.util.*;
class Solution {
public int solution(int a, int b, int c, int d) {
int[] dice = {a, b, c, d};
Map<Integer, Integer> count = new HashMap<>();
// 등장 횟수 세기
for (int x : dice) {
count.put(x, count.getOrDefault(x, 0) + 1);
}
// 1) 네 주사위 모두 같은 경우 (4)
if (count.size() == 1) {
int p = dice[0];
return 1111 * p;
}
// 2) 세 개가 같고 하나만 다른 경우 (3 + 1)
if (count.containsValue(3)) {
int p = 0, q = 0;
for (int key : count.keySet()) {
if (count.get(key) == 3) p = key;
else q = key;
}
return (int) Math.pow(10 * p + q, 2);
}
// 3) 두 개씩 같은 두 쌍 (2 + 2)
if (count.size() == 2) { // (2,2) 또는 (3,1)의 케이스
int[] keys = new int[2];
int idx = 0;
for (int key : count.keySet()) keys[idx++] = key;
int p = keys[0], q = keys[1];
if (count.get(p) == 2 && count.get(q) == 2) {
return (p + q) * Math.abs(p - q);
}
}
// 4) 어떤 숫자가 2번, 나머지 2개는 1번씩 (2,1,1)
if (count.containsValue(2)) {
int product = 1;
for (int key : count.keySet()) {
if (count.get(key) == 1) product *= key;
}
return product;
}
// 5) 전부 다른 경우 (1,1,1,1)
int min = Integer.MAX_VALUE;
for (int x : dice) min = Math.min(min, x);
return min;
}
}
Map 사용 : 키(key)와 값(value)을 짝으로 저장하는 자료 구조
ex) 3, 3, 2, 6
3 → 2번
2 → 1번
6 → 1번
=> Map을 사용하여 각 주사위의 값 횟수를 비교 할 수 있음
==> 숫자(key) → 등장 횟수(value)
Map 선언법 : Map <Integer, Integer> count = new HashMap<>();
map 메서드 : put / get / getOrDefault
가장 중요한 코드
for (int x : dice) {
count.put(x, count.getOrDefault(x, 0) + 1);
}
-> dice에 들어있는 만큼 반복, getOrDefault로 값 꺼낸 후 +1
