20220203_알고리즘

Minseok-Choi·2022년 2월 3일
0

알고리즘

목록 보기
11/13
post-thumbnail

프로그래머스_다트게임

  • 메서드를 분리하면서 불필요한 메서드가 생긴 점이 아쉽다.
  • 다른 사람의 풀이에는 스택을 이용해서 점수를 계산할 수 있게한 사람들이 많았다.
import java.util.*;
import java.util.stream.Collectors;

class Solution {
    public int solution(String dartResult) {
        Queue<String> input = Arrays.stream(dartResult.split("")).collect(Collectors.toCollection(LinkedList::new));
        List<Integer> scores = new ArrayList<>();
        while(scores.size() != 3) { // 다트는 총 3번 던짐
            saveScore(scores,input);
        }
        int answer = scores.stream().reduce(0,(x,y) ->(x+y)); // 점수 합산
        return answer;
    }

    private static void saveScore(List<Integer> scores, Queue<String> input) {
        String strNumber = input.poll();
        if(strNumber.equals("1")) { 
            if(input.peek().equals("0")) { // 점수가 10점일 경우
                strNumber += input.poll();
            }
        }
        int number = Integer.parseInt(strNumber);
        int score = 0;
        while (!input.isEmpty()) {

            if(input.peek().matches("[0-9]")) {
                break;
            }

            if(input.peek().matches("S|D|T")) { // 보너스
                int exponent = findExponent(input.poll());
                score = (int) Math.pow(number,exponent);
                continue;
            }

            if(input.peek().equals("*")) { // 옵션(스타)
                int option = findOption(input.poll());
                score = plusStarOption(scores,score,option);
                continue;
            }

            if(input.peek().equals("#")) { // 옵션(아차)
                int option = findOption(input.poll());
                score = plusAchaOption(score,option);
                continue;
            }

        }
        scores.add(score);
    }

    private static int findExponent(String bonus) {
        if(bonus.equals("S")) {
            return 1;
        }
        if(bonus.equals("D")) {
            return 2;
        }
        if(bonus.equals("T")) {
            return 3;
        }
        throw new IllegalArgumentException();
    }

    private static int findOption(String option) {
        if(option.equals("#")) {
            return -1;
        }
        if(option.equals("*")) {
            return 2;
        }
        throw new IllegalArgumentException();
    }

    private static int plusStarOption(List<Integer> scores, int score, int option) {
        if(!scores.isEmpty()) { 
            scores.set(scores.size()-1,scores.get(scores.size()-1)*option);
        }
        return score*option;
    }

    private static int plusAchaOption(int score, int option) {
        return score*option;
    }


}
profile
차곡차곡

0개의 댓글