[프로그래머스/C++]Lv.1 - [1차] 다트 게임

YH J·2023년 5월 27일
0

프로그래머스

목록 보기
100/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/17682

내 풀이

string 원소 하나하나 검사해가면서 숫자인지 SDT중 하나인지 #*중 하나인지 검사해서 유형에 맞게 처리한다.
10점인 경우 어차피 앞은 무조건1 뒤는 0이므로 따로 예외를 둘 필요는 없다

내 코드

#include <string>
#include <vector>
using namespace std;

int solution(string dartResult) {
    int answer = 0;
    string num = "";
    int index = 0;
    vector<int> nums;
    for(char s : dartResult)
    {
        if(isdigit(s))
            num += s;
        else if(s == 'S')
        {
            nums.push_back(stoi(num));
            num = "";
            index++;
        }
        else if(s == 'D')
        {
            nums.push_back(stoi(num) * stoi(num));
            num = "";
            index++;
        }
        else if(s == 'T')
        {
            nums.push_back(stoi(num) * stoi(num) * stoi(num));
            num = "";
            index++;
        }
        else if(s == '#')
        {
            nums[index - 1] *= (-1);
        }
        else if(s == '*')
        {
            nums[index - 1] *= 2;
            nums[index - 2] *= 2;
        }
    }
    for(int n : nums)
        answer += n;
    return answer;
}

다른 사람의 풀이

#include <string>
#include <sstream>
#include <cmath>

using namespace std;

int solution(string dartResult) {
    stringstream ss(dartResult);

    int sum[3] = { 0, 0, 0 };
    int options[3] = { 1, 1, 1 };
    for (int i = 0; i < 3; i++) {
        int score;
        char bonus;
        char option;

        ss >> score;

        bonus = ss.get();
        option = ss.get();

        if (option != '*' && option != '#') {
            ss.unget();
        }

        switch (bonus) {
        case 'S':
            sum[i] += pow(score, 1);
            break;
        case 'D':
            sum[i] += pow(score, 2);
            break;
        case 'T':
            sum[i] += pow(score, 3);
            break;
        default:
            break;
        }

        switch (option) {
        case '*':
            if (i > 0 && options[i - 1]) options[i - 1] *= 2;
            options[i] *= 2;
            break;
        case '#':
            options[i] = -options[i];
            break;
        default:
            break;
        }
    }

    return sum[0] * options[0] + sum[1] * options[1] + sum[2] * options[2];
}

다른 사람의 풀이 해석

stringstream을 사용하였다.
get()은 커서를 하나 옮기면서 값을 반환
unget() 커서를 이전으로 한칸 이동
일단 숫자부터 뺀 뒤 bonus와 option을 검사하는데 option이 *이나 #이 아니면(숫자면) unget()으로 뒤로 되돌린다.
그 후 bonus를 적용시킨뒤 option을 적용시킨다.
option은 미리 만들어둔 option배열에 적용시킨다.

profile
게임 개발자 지망생

0개의 댓글