[C++] 프로그래머스 주사위 게임 3

문제설명

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

• 네 주사위에서 나온 숫자가 모두 p로 같다면 1111 × p점을 얻습니다.

• 세 주사위에서 나온 숫자가 p로 같고 나머지 다른 주사위에서
  나온 숫자가 q(p ≠ q)라면 (10 × p + q)2점을 얻습니다.
• 주사위가 두 개씩 같은 값이 나오고,
  나온 숫자를 각각 p, q(p ≠ q)라고 한다면
  (p + q) × |p - q|점을 얻습니다.
• 어느 두 주사위에서 나온 숫자가 p로 같고
  나머지 두 주사위에서 나온 숫자가
  각각 p와 다른 q, r(q ≠ r)이라면 q × r점을 얻습니다.
• 네 주사위에 적힌 숫자가 모두 다르다면
  나온 숫자 중 가장 작은 숫자 만큼의 점수를 얻습니다.

네 주사위를 굴렸을 때 나온 숫자가
정수 매개변수 a, b, c, d로 주어질 때,
얻는 점수를 return 하는 solution 함수를 작성해 주세요.


제한사항

• a, b, c, d는 1 이상 6 이하의 정수입니다.


입출력 예

a b c d result
2 2 2 2 2222
4 1 4 4 1681
6 3 3 6 27
2 5 2 6 30
6 4 2 5 2


풀이

주사위 값에 따른 조건들을 구현하는 간단한 구현 문제입니다.

#include <string>
#include <vector>
#include <set>
#include <cmath>
#include <algorithm>

using namespace std;

int solution(int a, int b, int c, int d) {
    
    int answer = 0;
    
    set<int> arr;
    
    arr.insert(a);
    arr.insert(b);
    arr.insert(c);
    arr.insert(d);
    
    vector<int> num;
    
    num.push_back(a);
    num.push_back(b);
    num.push_back(c);
    num.push_back(d);
    
    if(arr.size() == 1)
    {
        answer = 1111 * a;
    }
    else if(arr.size() == 2)
    {
        int cnt = 0;
        
        for(int i = 0; i < 4; i++)
        {
            if(num[0] == num[i])
                cnt++;
        }
        
        if(cnt == 2)
        {
            int p = *(max_element(begin(num),end(num)));
            int q = *(min_element(begin(num),end(num)));
            
            answer = (p + q) * abs(p - q);
        }
        else
        {
            int p, q;
            
            for(int i = 0; i < 4; i++)
            {
                if(count(num.begin(), num.end(), num[i]) != 3)
                {
                    q = num[i];
                }
                else
                {
                    p = num[i];
                }
            }
            
            answer = pow(10 * p + q, 2);
        }
    }
    else if(arr.size() == 3)
    {
        answer = 1;
        
        for(int i = 0; i < 4; i++)
        {
            int cnt = 0;
            for(int j = 0; j < 4; j++)
            {
                if(i == j)
                    continue;
                
                if(num[i] == num[j])
                    cnt++;
            }
            if(cnt == 0)
                answer *= num[i];
        }
    }
    else
    {
        answer = *min_element(num.begin(), num.end());
    }
    
    return answer;
    
}


결과

코드 실행결과

Categories:

Updated:

Leave a comment