[프로그래머스] [1차] 다트 게임

fsm12·2023년 6월 28일
0

프로그래머스

목록 보기
23/57
post-thumbnail

문제링크

문제 이해

[ 입력형태 / 조건 ]

dartResult
"점수|보너스|[옵션]"으로 이루어진 문자열 3세트 | 1S2D*3T | 점수는 0에서 10 사이의 정수, 보너스는 S, D, T 중 하나, 옵선은 *이나 # 중 하나이며, 없을 수도 있음

[ 문제 ]

=> 총 3번의 다트게임에서 얻은 점수를 return

[ 풀이 ]

dartResult의 값을 숫자 / *,# / S,D,T 로 크게 3개의 분기점으로 나누고, 문제에서 요구한 방법대로 계산



코드

> [성공] 1차 시도 : int[] 이용

  • 생각한 풀이 그대로 구현
class Solution {
    public int solution(String dartResult) {
        int[] score = new int[3];
        
        int idx = 0;
        for(char c : dartResult.toCharArray()){
            if(Character.isDigit(c)){
                score[idx] = score[idx]*10 + (c - '0');
                continue;
            }
            
            if(c == '*'){
                score[idx-1]*=2;
                if(2<=idx){
                    score[idx-2]*=2;
                }
                continue;
            }
            
            if(c == '#'){
                score[idx-1]*=-1;
                continue;
            }
            
            if(c == 'D'){
                score[idx] = (int) Math.pow(score[idx], 2);
            }
            
            if(c == 'T'){
                score[idx] = (int) Math.pow(score[idx], 3);
            }
            
            idx++;
        }
        
        int ans = 0;
        for(int i=0; i<3; i++){
            ans += score[i];
        }
        return ans;
    }
}



> [성공] 2차 시도 : Pattern, Matcher 이용(정규식)

  • 패턴으로 추출해서 같은 로직으로 구현
import java.util.regex.*;

class Solution {
    public int solution(String dartResult) {
        Pattern pattern = Pattern.compile("([0-9]+)([SDT])([*#]?)");
        Matcher matcher = pattern.matcher(dartResult);
        
        int[] score = new int[3];
        int idx = 0;
        while(matcher.find()){
            score[idx] = Integer.parseInt(matcher.group(1));
            
            if(matcher.group(2).charAt(0) == 'D'){
                score[idx] = (int) Math.pow(score[idx], 2);
            }
            
            if(matcher.group(2).charAt(0) == 'T'){
                score[idx] = (int) Math.pow(score[idx], 3);
            }
            
            idx++;
            
            if(!matcher.group(3).isEmpty()){
                if(matcher.group(3).charAt(0) == '*'){
                    score[idx-1]*=2;
                    if(2<=idx){
                        score[idx-2]*=2;
                    }
                }

                if(matcher.group(3).charAt(0) == '#'){
                    score[idx-1]*=-1;
                }
            }
        }
        
        int ans = 0;
        for(int i=0; i<3; i++){
            ans += score[i];
        }
        return ans;
    }
}


=> 이 문제에서 얻을 수 있는 이점은 점수가 1~2자리가 가능하지만 경우에 관계없이 한번에 점수를 추출할 수 있다는 점 뿐이므로, 적합해 보이진 않음. 하지만 이처럼 여러 자료형의 조합이 까다로워 추출하는 게 애매할 경우 사용하면 좋을 것 같음.


TIP : 정규식을 이용해 패턴을 추출하여 단순하게 구현하는 방식도 있다.

0개의 댓글