이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

다트 게임

출처 : http://tech.kakao.com/2017/09/27/kakao-blind-recruitment-round-1/

2018년 카카오 신입 공채 1차 코딩 테스트 문제입니다.


카카오톡 게임별의 하반기 신규 서비스로 다트 게임을 출시하기로 했다. 다트 게임은 다트판에 다트를 세 차례 던져 그 점수의 합계로 실력을 겨루는 게임으로, 모두가 간단히 즐길 수 있다. 갓 입사한 무지는 코딩 실력을 인정받아 게임의 핵심 부분인 점수 계산 로직을 맡게 되었다. 다트 게임의 점수 계산 로직은 아래와 같다.

  1. 다트 게임은 총 3번의 기회로 구성된다.
  2. 각 기회마다 얻을 수 있는 점수는 0점에서 10점까지이다.
  3. 점수와 함께 Single(S), Double(D), Triple(T) 영역이 존재하고 각 영역 당첨 시 점수에서 1제곱, 2제곱, 3제곱 (점수^1 , 점수^2 , 점수^3 )으로 계산된다.
  4. 옵션으로 스타상(*) , 아차상(#)이 존재하며 스타상(*) 당첨 시 해당 점수와 바로 전에 얻은 점수를 각 2배로 만든다. 아차상(#) 당첨 시 해당 점수는 마이너스된다.
  5. 스타상(*)은 첫 번째 기회에서도 나올 수 있다. 이 경우 첫 번째 스타상(*)의 점수만 2배가 된다. (예제 4번 참고)
  6. 스타상(*)의 효과는 다른 스타상(*)의 효과와 중첩될 수 있다. 이 경우 중첩된 스타상(*) 점수는 4배가 된다. (예제 4번 참고)
  7. 스타상(*)의 효과는 아차상(#)의 효과와 중첩될 수 있다. 이 경우 중첩된 아차상(#)의 점수는 -2배가 된다. (예제 5번 참고)
  8. Single(S), Double(D), Triple(T)은 점수마다 하나씩 존재한다.
  9. 스타상(*), 아차상(#)은 점수마다 둘 중 하나만 존재할 수 있으며, 존재하지 않을 수도 있다.

0~10의 정수와 문자 S, D, T, *, #로 구성된 문자열이 입력될 시 총점수를 반환하는 함수를 작성하라.

입력 형식

“점수|보너스|[옵션]”으로 이루어진 문자열 3세트.

예) 1S2D*3T
  • 점수는 0에서 10 사이의 정수이다.
  • 보너스는 S, D, T 중 하나이다.
  • 옵선은 *이나 # 중 하나이며, 없을 수도 있다.

출력 형식

3번의 기회에서 얻은 점수 합계에 해당하는 정수값을 출력한다.

예) 37

입출력 예제

예제 dartResult answer 설명
1 1S2D*3T 37 1^1 * 2 + 2^2 * 2 + 3^3
2 1D2S#10S 9 1^2 + 2^1 * (-1) + 10^1
3 1D2S0T 3 1^2 + 2^1 + 0^3
4 1S*2T*3S 23 1^1 * 2 * 2 + 2^3 * 2 + 3^1
5 1D#2S*3S 5 1^2 * (-1) * 2 + 2^1 * 2 + 3^1
6 1T2D3D# -4 1^3 + 2^2 + 3^2 * (-1)
7 1D2S3T* 59 1^2 + 2^1 * 2 + 3^3 * 2
입사문제 카카오

2017/10/07 16:13

pahkey

입출력 예제에서 4번 1S2T3S의 answer가 23이 되는 이유가 궁금합니다. 본 예제는 스타상 아차상이 존재하지 않으므로 * 2 가 붙을 이유가 없습니다. - kihyun lee, 2017/10/08 03:41
문제 입력오타가 있었습니다. 알려주셔서 감사합니다. - pahkey, 2017/10/08 16:38

38개의 풀이가 있습니다.

import re


def dart(inp):
    shot = re.findall(r'\d{1,2}[SDT][*#]?', inp)

    opt = [1,1,1]
    for i, s in enumerate(shot):
        if s[-1] == '#':
            opt[i] *= -1
            shot[i] = shot[i][:-1]
        elif s[-1] == '*':
            opt[i] *= 2
            shot[i] = shot[i][:-1]
            if i:
                opt[i-1] *= 2

    point = [(int(s[:-1]) ** '0SDT'.find(s[-1]) * o) for s, o in zip(shot, opt)]

    return sum(point)


print(dart('1S2D*3T'))
print(dart('1D2S#10S'))
print(dart('1D2S0T'))
print(dart('1S*2T*3S'))
print(dart('1D#2S*3S'))
print(dart('1T2D3D#'))
print(dart('1D2S3T*'))

2017/10/11 17:08

songci

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("입력");
        int cnt=0;
        String input = sc.next();
        char [] inputC = input.toCharArray();

        for(char a : inputC)    //항의 갯수
            if(a=='S' || a=='D' || a=='T')
                cnt++;

        int [] answer_arr = new int[cnt];

        for(int i=1,j=0;i<inputC.length;i++){
            if(inputC[i]=='S' || inputC[i]=='D' || inputC[i]=='T'){
                if(inputC[i]=='S'){
                    if(inputC[i-1]=='0' && inputC[i-2]=='1'){
                        answer_arr[j]=10;
                    }else{
                        Character a1 = new Character(inputC[i-1]);
                        answer_arr[j] = Integer.parseInt(a1.toString());
                    }
                }else if(inputC[i]=='D'){
                    if(inputC[i-1]=='0' && inputC[i-2]=='1'){
                        answer_arr[j]=10;
                    }else{
                    Character a1 = new Character(inputC[i-1]);
                    answer_arr[j] = (int)Math.pow(Integer.parseInt(a1.toString()), 2);  
                    }
                }else if(inputC[i]=='T'){
                    if(inputC[i-1]=='0' && inputC[i-2]=='1'){
                        answer_arr[j]=10;
                    }else{
                    Character a1 = new Character(inputC[i-1]);
                    answer_arr[j] = (int)Math.pow(Integer.parseInt(a1.toString()), 3);
                    }
                }
                j++;
            }
            if(inputC[i]=='*'){
                if(j==1){
                    answer_arr[0]*=2;
                }else{
                    for(int k=j;k>j-2;k--){
                        answer_arr[k-1]*=2;
                    }
                }           
            }
            if(inputC[i]=='#'){
                    answer_arr[j-1] = answer_arr[j-1]*-1;
            }
        }

        int sum = 0;
        for(int a : answer_arr){
            sum+=a;
        }
        System.out.println(sum);
    }

맞는지 틀린지를 잘 모르겠네요 또 맞다고해도 더 깔끔하게 짜는 방법이 있을 것 같습니다. 고수님들의 지적을 기다립니다.

2017/10/08 03:43

kihyun lee

import re
inp, result = input("input : "), []
p = re.compile("\d+[SDT][*#]?")
lst = p.findall(inp)                         #정규표현식으로 각 시행 결과를 리스트로 나눕니다
for i in range(0, 3) :
    if lst[i][-1] == '*' :                   #먼저 *를 처리합니다(SDT를 먼저 처리하면 그 결과에 *가 포함되므로)
        lst[i] = lst[i].replace('*', '*2')
        if i != 0 :
            lst[i-1] += '*2'
    lst[i] = lst[i].replace('S', '**1').replace('D', '**2').replace('T', '**3').replace('#', '*(-1)')
    #SDT 및 #를 수식과 바꿉니다
print("+".join(lst),'=', eval("+".join(lst))) #바꾼 문자열을 계산합니다

결과

input : 1D#2S*3S

12(-1)2+212+3*1 = 5

2019/10/11 14:42

GG

Ruby

토큰화, 룰적용, eval.

def play_dart(str)
  op = "SDT*#".chars.zip(%w(**1 **2 **3 *2 *-1)).to_h
  rule = ->s,e { e[0] != "*" ? s<<e : (t = s.pop(e[-1].to_i).map{|_|_+e}; s+t) }
  tokens = str.chars.sum("") {|c| op.has_key?(c) ? op[c]+" " : c}.split
  eval tokens.reduce([], &rule).join("+")
end

Test

cases = %w(1S2D*3T 1D2S#10S 1D2S0T 1S*2T*3S 1D#2S*3S 1T2D3D# 1D2S3T*)
expect( cases.map {|e| play_dart(*e) } ).to eq [37, 9, 3, 23, 5, -4, 59]

2017/10/08 13:42

rk

입출력 예제의 테스트케이스대로 나오긴 하네여. 수정,보완 조언좀 부탁드려요.

public class dart {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int point;
        String bonus;
        String option;
        int answer=0;
        int firstpoint=0;
        int secondpoint=0;
        int thirdpoint=0;
        StringBuffer dartResult = new StringBuffer();
        for(int i=0;i<3;i++){

            switch (i) {

                case 0 :
                    while(true){
                        System.out.println("점수 입력 : ");
                        point = sc.nextInt();
                        if(!(point>=0 && point<=10)){
                            System.out.println("점수는 0에서 10점 사이의 정수 입니다.");
                        }else{
                            break;
                        }
                    }
                    sc.nextLine();
                    while(true){
                        System.out.println("보너스 입력(보너스는 S,D,T 중 하나) : ");
                         bonus = sc.nextLine();
                        if(!(bonus.equals("S") || bonus.equals("D") || bonus.equals("T"))){
                            System.out.println("S나 D나 T입력해주셈");
                        }else{
                            break;
                        }
                    }
                    if(bonus.equals("S")){
                        firstpoint = point;
                    }else if(bonus.equals("D")){
                        firstpoint= point*point;
                    }else{
                        firstpoint =point*point*point;
                    }
                    System.out.println("옵션입력 : ");

                    option = sc.nextLine();
                    if(option.equals("*")){
                        firstpoint = firstpoint*2;
                    }else if(option.equals("#")){
                        firstpoint = firstpoint*-1;
                    }
                    dartResult.append(String.valueOf(point)+bonus+option);
                    break;
                case 1 :
                    while(true){
                        System.out.println("점수 입력 : ");
                        point = sc.nextInt();
                        if(!(point>=0 && point<=10)){
                            System.out.println("점수는 0에서 10점 사이의 정수 입니다.");
                        }else{
                            break;
                        }
                    }
                    sc.nextLine();
                    while(true){
                        System.out.println("보너스 입력(보너스는 S,D,T 중 하나) : ");
                         bonus = sc.nextLine();
                        if(!(bonus.equals("S") || bonus.equals("D") || bonus.equals("T"))){
                            System.out.println("S나 D나 T입력해주셈");
                        }else{
                            break;
                        }
                    }
                    if(bonus.equals("S")){
                        secondpoint = point;
                    }else if(bonus.equals("D")){
                        secondpoint= point*point;
                    }else{
                        secondpoint =point*point*point;
                    }
                    System.out.println("옵션입력 : ");

                    option = sc.nextLine();
                    if(option.equals("*")){
                        secondpoint = secondpoint*2;
                        firstpoint = firstpoint*2;
                    }else if(option.equals("#")){
                        secondpoint = secondpoint*-1;
                    }
                    dartResult.append(String.valueOf(point)+bonus+option);
                    break;
                case 2 :
                    while(true){
                        System.out.println("점수 입력 : ");
                        point = sc.nextInt();
                        if(!(point>=0 && point<=10)){
                            System.out.println("점수는 0에서 10점 사이의 정수 입니다.");
                        }else{
                            break;
                        }
                    }
                    sc.nextLine();
                    while(true){
                        System.out.println("보너스 입력(보너스는 S,D,T 중 하나) : ");
                         bonus = sc.nextLine();
                        if(!(bonus.equals("S") || bonus.equals("D") || bonus.equals("T"))){
                            System.out.println("S나 D나 T입력해주셈");
                        }else{
                            break;
                        }
                    }
                    if(bonus.equals("S")){
                        thirdpoint = point;
                    }else if(bonus.equals("D")){
                        thirdpoint= point*point;
                    }else{
                        thirdpoint =point*point*point;
                    }
                    System.out.println("옵션입력 : ");

                    option = sc.nextLine();
                    if(option.equals("*")){
                        thirdpoint = thirdpoint*2;
                        secondpoint = secondpoint*2;
                    }else if(option.equals("#")){
                        thirdpoint = thirdpoint*-1;
                    }
                    dartResult.append(String.valueOf(point)+bonus+option);
                    break;
            }

        }
        answer = firstpoint+secondpoint+thirdpoint;
        System.out.println(dartResult+"   " +answer);
    }


}

2017/10/11 13:39

김문수

C++풀이입니다.

180907 수정해보았습니다.

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

int main()
{
    string str;
    cin >> str;

    //S D제곱 T 세제곱
    //*을 만나면 이전에 받은 스코어 두배 # -1곱합
    //점수는 0~10

    int answer = 0;
    int score = 0;

    for (int i = 0; i < str.length(); i++)
    {
        //숫자
        if (str.substr(i, 1) >= "0" && str.substr(i, 1) <= "9")
        {
            //cout << str.substr(i, 1);
            //10인경우
            if (str.substr(i, 2) == "10")
            {
                i++;
                score = 10;
            }
            else
            {
                score = atoi(str.substr(i, 1).c_str());
            }
        }
        else //스코어곱, 보너스 문자
        {
            if (str.substr(i, 1) == "S")
            {
                if (str.substr(i + 1, 1) == "*")
                {
                    i++;
                    score *= 2;
                }
                else if (str.substr(i + 1, 1) == "#")
                {
                    i++;
                    score *= -1;
                }
            }
            else if (str.substr(i, 1) == "D")
            {
                score *= score;

                if (str.substr(i+1, 1) == "*")
                {
                    i++;
                    score *= 2;
                }
                else if (str.substr(i+1, 1) == "#")
                {
                    i++;
                    score *= -1;
                }
            }
            else if (str.substr(i, 1) == "T")
            {
                int temp = score;
                score *= temp;
                score *= temp;

                if (str.substr(i + 1, 1) == "*")
                {
                    i++;
                    score *= 2;
                }
                else if (str.substr(i + 1, 1) == "#")
                {
                    i++;
                    score *= -1;
                }
            }
            answer += score;
        }
        cout << str.substr(i, 1) << endl;
        cout << "answer" << answer << endl;
    }
    cout << answer;
}

2017/10/15 18:51

와디더


def dart(s):
    score = []
    n = ''
    for c in s:
        if c.isnumeric():
            n += c
        elif c == 'S':
            score.append(int(n) ** 1)
            n = ''
        elif c == 'D':
            score.append(int(n) ** 2)
            n = ''
        elif c == 'T':
            score.append(int(n) ** 3)
            n = ''
        elif c == '*':
            if len(score) > 1:
                score[-2] *= 2
            score[-1] *= 2
        elif c == '#':
            score[-1] *= -1
        # print(c, score)
    print(s, sum(score))


2017/10/16 13:34

박범수

POINTS = ("0".."10").to_a
ZONES = ["S", "D", "T"]
AWARDS = ["*", "#"]

class String
  def point?
    POINTS.each { |p| return true if p == self }
    false
  end

  def zone?
    ZONES.each { |p| return true if p == self }
    false
  end

  def award?
    AWARDS.each { |p| return true if p == self }
    false
  end
end

class DartGame

  def initialize(games)
    @games = games.split('')
    @zones = ZONES.each_with_index.to_h
  end

  def calculate
    results = []
    starting = 0
    @games.each_with_index do |s, i|
      next unless s.zone?

      point = 0
      if i - starting == 1
        point = @games[i-1].to_i
      elsif i - starting == 2
        point = (@games[i-2] + @games[i-1]).to_i
      end

      point_zone = 1
      (@zones[s]+1).times do
        point_zone *= point
      end
      results << point_zone

      break if @games[i+1].nil?

      if @games[i+1].award?
        len = results.length
        case @games[i+1]
          when '*'
            results = results.each_with_index.map { |r, k| r * 2 if k > len - 3 }
            starting = i + 2
          when '#'
            results[len - 1] = results.last * -1
            starting = i + 2
          else
            starting = i + 1
        end
      else
        starting = i + 1
      end
    end
    puts results.inject(:+)
  end

end

game = DartGame.new(gets.chomp)
game.calculate

영역의 경우는 항상 1자리이고, 반드시 거치므로 영역을 기준으로 계산하면서 시작점을 바꿔가는 방식을 취했습니다. 너무 길긴하네요.

2017/10/21 22:00

이한결

파이썬3.6입니다. 정규식으로 입력을 분해해서 규칙에 따라 계산합니다.

def dart(s):
    pat = re.compile(r'([0-9]|10)([SDT])([\*#]?)')
    temp = []
    proc = {'S': lambda x: x, 'D': lambda x: x*x, 'T': lambda x: x**3}
    for n, t, b in pat.findall(s):
        p = proc[t](int(n))
        if b == '#':
            p *= -1
        elif b == '*':
            p *= 2
            if temp:
                temp[-1] *= 2
        temp.append(p)
    return sum(temp)

2017/10/24 13:16

룰루랄라

import java.util.Stack;
import java.math.*;

    public static int calGrade(String exp)
    {
        char[] exps = exp.toCharArray();
        Stack<Integer> stack = new Stack<Integer>();
        for(char e : exps)
        {
            try{
                switch(e)
                {
                case '*':
                    int popResult = stack.pop() * 2;
                    if(stack.size() != 0)
                        stack.push(stack.pop() * 2);
                    stack.push(popResult);
                    break;
                case '#':
                    stack.push(stack.pop() * -1);
                    break;
                case 'S':
                    stack.push((int)Math.pow(stack.pop(), 1));
                    break;
                case 'D':
                    stack.push((int)Math.pow(stack.pop(), 2));
                    break;
                case 'T':
                    stack.push((int)Math.pow(stack.pop(), 3));
                    break;
                case '0':
                    if(stack.peek() == 1)
                    {
                        stack.pop();
                        stack.push(10);
                    } else 
                        stack.push(0);
                    break;
                default:                
                    String s = String.valueOf(e);
                    stack.push(Integer.parseInt(s));
                    break;
                }
            }           
            catch(NumberFormatException exception){
                System.out.println(exp +"는 정확한 입력값이 아닙니다. 올바른 값을 넣어주세요.");
                System.exit(0);
            }
        }

        int result = 0;
        while(!stack.isEmpty())
            result += stack.pop();
        return result;  
    }

2017/10/25 11:45

김홍규

def dart(char):
    char = list(char)
    count =[]
    grade=0
    for i in range(len(char)):
        if char[i].isdigit() :
            if char[i]=='1' and char[i+1] =='0': char[i]='10'
            if char[i]=='0' and char[i-1] == '1' : continue
            count = count + [grade]
            grade = int(char[i])
        elif char[i] == 'S' : grade = grade
        elif char[i] == 'D' : grade = grade**2
        elif char[i] == 'T' : grade = grade**3
        elif char[i] == '*' : 
            grade = 2*grade
            count[len(count)-1] = count[len(count)-1]*2
        elif char[i] == '#' : grade = grade*-1
    count += [grade]
    return(sum(count))

dart('1D2S0T'), dart('1S*2T*3S'), dart('1D#2S*3S'), dart('1T2D3D#'), dart('1D2S3T*')

python 3.52 입니다

2017/11/24 19:30

Seohyun Choi

import java.util.*;
import java.util.regex.*;

public class dart {
    static int[] totalScore = new int[3];
    public int calcScore_num(String score) {
        int totalScore = 0;
        Pattern p = Pattern.compile("([0-9]+)([D,S,T])");
        Matcher m = p.matcher(score);
        while(m.find()) {
            if(m.group(2).matches("S")) {
                totalScore = Integer.parseInt(m.group(1));
            } else if(m.group(2).matches("D")) {
                totalScore = Integer.parseInt(m.group(1)) * Integer.parseInt(m.group(1));
            } else if (m.group(2).matches("T")) {
                totalScore = Integer.parseInt(m.group(1)) * Integer.parseInt(m.group(1)) * Integer.parseInt(m.group(1));
            }
        }
        return totalScore;
    }

    public void calcScore_star(int i) {
        for(int j = 0; j <= 1; j++) {
            totalScore[i] = totalScore[i]*2;
            if(i==0) {
                break;
            }
            i = i-1;
        }
    }

    public void calcScore_sharp(int i) {
            totalScore[i] = totalScore[i]*(-1);
    }

    public void calcScore(String score) {
        Pattern p = Pattern.compile("([0-9]+[D,S,T])([*,#]*)");
        Matcher m = p.matcher(score);

        int i = 0;
        while(m.find()) {
            totalScore[i] = this.calcScore_num(m.group(1));
            if(m.group(2).matches("\\*")) {
                this.calcScore_star(i);
            }
            if(m.group(2).matches("#")) {
                this.calcScore_sharp(i);
            }   
            i++;
        }
        System.out.println(totalScore[0]+totalScore[1]+totalScore[2]);
    }

    public static void main(String[] args) {
        dart d = new dart();
        String score = "1S2D*3T";
        d.calcScore(score);
        String score2 = "1D2S#10S";
        d.calcScore(score2);
        String score3 = "1D2S0T";
        d.calcScore(score3);
        String score4 = "1S*2T*3S";
        d.calcScore(score4);
        String score5 = "1D#2S*3S";
        d.calcScore(score5);
        String score6 = "1T2D3D#";
        d.calcScore(score6);
        String score7 = "1D2S3T*";
        d.calcScore(score7);
    }

}

고수님들 피드백 부탁드립니다.

2017/12/01 15:46

연지민

파이썬 버전 3.6입니다.

import re
def CalScore(dartstr) :
    # 게임별, 정보별 그룹핑
    p = re.compile('(\d+)([SDT])([*#]?)')
    m = p.findall(dartstr)

    dic_bonus = {'S':1, 'D':2, 'T':3}  # 문자별 Bonus 승수 Dictionary
    dic_prize = {'*':2, '#':-1}        # 문자별 Prize 배수 Dictionary
    game_score = []
    game_no = 0

    # 입력 정보의 정합성 체크는 생략

    while game_no < len(m) : # game별 Loop
        # 게임별 점수 셋팅
        game_score.append(int(m[game_no][0]) ** dic_bonus[m[game_no][1]])

        if(m[game_no][2] != "") : # 3번째 정보(상/벌)가 유입된 경우
            if game_no >= 1 : # 두번 째 게임 이상 인 경우
                if m[game_no][2] == '*' : # 상일 경우 이전 점수에도 반영
                    game_score[game_no-1] = game_score[game_no-1] * dic_prize[m[game_no][2]] # 이전 점수 변경
            game_score[game_no] = game_score[game_no] * dic_prize[m[game_no][2]] # 현재 점수 변경
        game_no += 1
    return sum(game_score)

2017/12/05 13:54

Young

import re
point=input()
p=re.compile("[0-9]+[SDT*#]+")
result=p.findall(point)
sum=0
def calcul(n):
    result=0
    command=""
    if "10" in n:
        command=n[2:]
        result=10
    else:
        command=n[1:]
        result=int(n[0])
    for i in command:
        if i=="S":
            result=result**1
        if i=="D":
            result=result**2
        if i=="T":
            result=result*result*result
        if i=="*" and "#" not in command:
            result=result*2
        if i=="#" and "*" not in command:
            result=result*-1
        if i=="*" and "#" in command:
            result=result*-2
        if i=="#" and "*" in command:
            result=result*-2
    return result
for i in result:
    sum=sum+calcul(i)
if "*" in result[1]:
    sum=sum+calcul(result[0])
if "*" in result[2]:
    sum=sum+calcul(result[1])


print(sum)

2017/12/25 19:31

Dr.Choi

#include<stdio.h>


int main(void)
{
    char ACG = '1';
    int grade[3], count = 0, i;

    while(ACG != '\n')
    {   
        scanf("%c", &ACG) ;
        if(ACG == 'S')
            {
                grade[count-1] = grade[count-1];
                i = 0;}
        else if(ACG == 'D')
        {grade[count-1] *=grade[count-1];i = 0;}
        else if(ACG == 'T')
        {grade[count-1] = grade[count-1]*grade[count-1]*grade[count-1];i = 0;}
        else if(ACG == '*')
        {i = 0;
            if(count == 1 )
            {
                grade[count-1] *=2;
            }
            else
                for(i = count-2 ;i < count; i++)
                    grade[i] *= 2;
        }

        else if(ACG == '#')

        {grade[count-1] *= -1;i = 0;}

        else if( ACG != '\n')
        {
            if(ACG-'0' == 1)
                {
                    i = 1;
                }

            if( i == 1 &&ACG == '0')
            {
                grade[count-1] = 10;

                continue;
            }

            count ++;
            grade[count -1] = ACG-'0';
        }

    }

    printf("%d",grade[0]+grade[1]+grade[2]);
}

2017/12/28 22:22

CodingMan

파이썬 3.6

def dartgame(data):
    tmp,games,play,score,score_list = [],[],[],0,[]
    for index,i in enumerate(data): # 입력받은 게임정보를 각 게임별로 구분
        if index != 0 and i.isdigit() and data[index-1].isdigit() is not True:
            games.append(''.join(tmp))
            tmp = []
            tmp.append(i)
        else:
            tmp.append(i)
    games.append(''.join(tmp))
    tmp = []
    for game in games: # 각 게임을 [점수,보너스,옵션] 으로 세분화
        for i in game:
            if not i.isdigit():
                play.append(''.join(tmp))
                tmp = []
                tmp.append(i)
            else:
                tmp.append(i)
        play.append(''.join(tmp))
        tmp = []
        if play[1] == 'D': # 각 게임의 스코어 계산
            score += int(play[0])*int(play[0])
        elif play[1] == 'T':
            score += int(play[0])*int(play[0])*int(play[0])
        else:
            score += int(play[0])
        if len(play) == 3:
            if play[2] == '*':
                score *= 2
                if score_list:
                    score_list[-1] = score_list[-1]*2
            elif play[2] == '#':
                score = sum(score_list)-score
                score_list = []
        score_list.append(score)
        play,score = [],0
    print(data,sum(score_list))

if __name__ == "__main__":
    dataset = ['1S2D*3T','1D2S#10S','1D2S0T','1S*2T*3S','1D#2S*3S','1T2D3D#','1D2S3T*']
    for data in dataset:
        dartgame(data)
  • 결과값
1S2D*3T 37
1D2S#10S 9
1D2S0T 3
1S*2T*3S 23
1D#2S*3S 5
1T2D3D# -4
1D2S3T* 59

2018/02/15 17:54

justbegin

package solr.example.solr.example;

public class Dart {

public static void main(String[]args) {
    final int CHANCE = 3;
    final int SCORE = 11;
    String [] score = new String[CHANCE];
    String [] bonus = {"S","D","T"};
    String [] option = {"*","#",""};

    for(int i=0;i<CHANCE;i++) {
        String tried = "";
        tried += String.valueOf((int)(Math.random()*SCORE));
        tried += bonus[(int)(Math.random()*CHANCE)];
        tried += option[(int)(Math.random()*CHANCE)];
        score[i]=tried;
    }
    int [] scores = new int [CHANCE];
    int last = 0;

    for(int i=0;i<score.length;i++) {
        int real = 0;
        int sut = (int)score[i].charAt(0)-48;

        if(score[i].contains("S")) {
            real += Math.pow(sut,1);
        }
        if(score[i].contains("D")) {
            real += Math.pow(sut,2);
        }
        if(score[i].contains("T")) {
            real += Math.pow(sut,3);
        }
        scores[i]=real;

        if(score[i].contains("*")) {
            if(i == 0) {
                scores[i]*=2;
            }else {                 
                if(score[i-1].contains("*")) {
                    scores[i]*=4;
                    scores[i-1]*=4;
                }else {
                    scores[i]*=2;
                    scores[i-1]*=2;
                }
            }
        }
        if(score[i].contains("#")) {    
            if(i ==0) {
                scores[i]=-scores[i];
            }else {
                if(score[i-1].contains("*")) {
                    scores[i]=-scores[i]*2;                 
                }else {
                    scores[i]=-scores[i];
                }   
            }
        }           
    }//end for
    for(int s:scores) {
        System.out.print(s+" ");
        last+=s;
    }
    System.out.println();
    System.out.println("점수="+last);
}

}

2018/02/19 17:50

윤재욱

def dart(a):
    num_index = list()
    for i in range(2,len(a)):
        if not(a[i-1] in '0123456789') and a[i] in '0123456789':
            num_index.append(i)
    b = [a[:num_index[0]], a[num_index[0]:num_index[1]], a[num_index[1]:]]
    c = list()
    option_index = list()
    ten_index = list()
    for i in range(3):
        if (b[i][1] != '0' and len(b[i]) == 3) or len(b[i]) == 4:
            option_index.append(i)
        if b[i][1] == '0':
            ten_index.append(i)
    for i in range(3):
        if i in ten_index:
            if 'S' in b[i]:
                c.append(10)
            elif 'D' in b[i]:
                c.append(100)
            else:
                c.append(1000)
        else:
            if 'S' in b[i]:
                c.append(int(b[i][0]))
            elif 'D' in b[i]:
                c.append(int(b[i][0]) ** 2)
            else:
                c.append(int(b[i][0]) ** 3)
    for j in option_index:
        if b[j][len(b[j])-1] == '#':
            c[j] = -1*c[j]
    for j in option_index:
        if b[j][len(b[j])-1] == '*':
            if j == 0:
                c[j] = 2 * c[j]
            else:
                (c[j-1], c[j]) = (2*c[j-1], 2*c[j])
    return sum(c)

2018/02/23 10:51

김동하

파이썬입니다. 한글자씩 끊어서 받았는데 숫자 10 때문에 8줄을 더 썼네요. 불만스러운데 줄일 방법을 모르겠네요.

def dart(x):
    grade = list()
    i=-1
    a=0
    xev = [1, 1, 1]

    for c in x: 
        if c == '#':
            xev[i] *= -1
        elif c == '*':
            if i == 0:
                xev[0] *= 2
            else:
                xev[i-1] *= 2
                xev[i] *= 2
        else:
            if c == 'S':
                grade.append(1)
                a=0
            elif c == 'D':
                grade.append(2)
                a=0
            elif c == 'T':
                grade.append(3)
                a=0
            else: 
                if a == 1 :
                    grade.pop()
                    grade.append(10)
                else :
                    grade.append(int(c))
                a += 1
                i += 1
    return (grade[0]**grade[1]*xev[0] + grade[2]**grade[3]*xev[1] + grade[4]**grade[5]*xev[2])

print(dart("1S2D*3T"))
print(dart("1D2S#10S"))
print(dart("1S*2T*3S"))
print(dart("1D#2S*3S"))
print(dart("1T2D3D#"))
print(dart("1D2S3T*"))

2018/03/08 00:02

노간

public int GetScore(string text)
    {
        char[] chararr = text.ToCharArray(); //string을 char 배열로 변경

        int[] scores = new int[3]; // 점수가 3번 들어가므로 각 점수를 계산할 배열 생성
        int arridx = 0; // 점수가 계산되는 배열인덱스
        try
        {
            for (int i = 0; i < chararr.Length; ++i)
            {
                if (char.IsNumber(chararr[i]))
                {
                    scores[arridx++] = Convert.ToInt32(chararr[i].ToString());
                    if(chararr[i]== '1' && chararr[i + 1] == '0')
                    {
                        i++;
                        scores[arridx - 1] = 10;
                    }

                }
                else
                {
                    switch (chararr[i])
                    {
                        case 'S':
                            scores[arridx - 1] *= 1;
                            break;
                        case 'D':
                            scores[arridx - 1] *= scores[arridx - 1];
                            break;
                        case 'T':
                            scores[arridx - 1] *= (scores[arridx - 1] * scores[arridx - 1]);
                            break;
                        case '*':
                            scores[arridx - 1] *= 2;
                            if (arridx - 2 >= 0)
                            {
                                scores[arridx - 2] *= 2;
                            }
                            break;
                        case '#':
                            scores[arridx - 1] *= -1;
                            break;
                    }
                }


            }
        }
        catch(IndexOutOfRangeException)
        {
            Debug.Log(arridx);
            return 0;
        }
        catch
        {
            return 0;
        }

        if (arridx < 2)
        {
            Debug.Log("Input Error");
            return 0;
        }

        int sumscore = 0;
        for (int i = 0; i < scores.Length; ++i)
        {
            sumscore += scores[i];
        }



        Debug.Log(text + " / " + scores[0] + " / " + scores[1] + " / " + scores[2] + " / " + sumscore);

        return sumscore;
    }

2018/03/24 17:34

Jaewoo Lee

import java.util.regex.*;

public class test4 {
    public static void main(String[] args) {
        String[] in_val = new String[] {"1S2D*3T","1D2S#10S","1D2S0T","1S*2T*3S","1D#2S*3S","1T2D3D#","1D2S3T*"};
        Pattern p1 = Pattern.compile("[0-9]");      // 숫자패턴
        Pattern p2 = Pattern.compile("[S,D,T]");    // 배점패턴
        Pattern p3 = Pattern.compile("[*,#]");      // 옵션패턴

        for (int x=0; x<in_val.length; x++) {
            String s_num = "";
            int cursor = 0;
            int[] num = new int[] {0,0,0};  // 숫자와 배점을 계산한 값
            int[] calc = new int[] {1,1,1}; // 옵션을 계산한 값
            int result = 0;

            for (int y = 0; y < in_val[x].length(); y++) {
                String v = String.valueOf(in_val[x].charAt(y));

                if (p1.matcher(v).find()) {
                    // 숫자 계산
                    if ("".equals(s_num)) {
                        s_num = v;
                    } else {
                        s_num += v;
                    }
                } else if (p2.matcher(v).find()) {
                    // 배점 계산
                    int square = ("S".equals(v)) ? 1 : ("D".equals(v)) ? 2 : 3;
                    num[cursor] = (int)Math.pow(Double.parseDouble(s_num), square);
                    s_num = "";
                    cursor++;
                } else if (p3.matcher(v).find()) {
                    // 옵션 계산
                    if ("*".equals(v)) {
                        int start = (cursor - 2 < 0) ? 0 : cursor - 2;
                        int end = cursor - 1;
                        for (int z = start; z <= end; z++) {
                            calc[z] *= 2;
                        }
                    } else if ("#".equals(v)) {
                        calc[cursor - 1] *= -1;
                    }
                }
            }

            // 결과값 계산
            for (int y = 0; y < num.length; y++) {
                result += num[y] * calc[y];
            }
            System.out.println("dartResult : " + in_val[x] + ",   answer : " + result);
        }
    }
}

2018/04/08 01:27

홍성욱

object Main extends App {
    def dartGame(s:String):Int = {
        var ans = Array.fill(3)(0)
        def loop(str:String, step:Int):Unit = {
            println(ans.toList)
            if(str.isEmpty)()
            else{
            str.head match {
                case '*' => {
                    if(step - 1 >= 0) ans(step - 1) *=  2
                    ans(step) *= 2
                    loop(str.tail, step)
                } 
                case '#' =>{
                    ans(step) *= -1
                    loop(str.tail, step)

                }
                case 'S' => loop(str.tail, step)

                case 'D' => {
                    ans(step) = Math.pow(ans(step), 2).toInt
                    loop(str.tail, step)
                }
                case 'T' => {
                    ans(step) = Math.pow(ans(step), 3).toInt
                    loop(str.tail, step)
                }

                case '1' => if(str.length >=2 && str(1) == '0'){
                        ans(step+1) = 10
                        loop(str.drop(2), step+1)
                    }
                    else{
                        ans(step+1) = 1
                        loop(str.tail, step+1)
                    }

                case x if(str.head >= '0' || str.head <= '9') => {
                        ans(step+1) = str.head.toInt - 48
                        loop(str.tail, step+1)
                    }
            }}

        }
        loop(s, -1)
        ans.sum
    }
    println(dartGame("1S*2T*3S"))
}

2018/04/17 22:09

한강희

package codingdojang;

import java.util.Scanner;

public class ex152 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);

        String n = sc.nextLine();
        int count = 0;


        int point[] = new int[n.length()];

        for(int i=0; i<n.length(); i++) {
            if(n.charAt(i) == 'S') {
                if(n.charAt(i-1) == '0' && n.charAt(i-2) == '1') {
                    point[count++] = 10;
                }
                else {
                    point[count++] = n.charAt(i-1)-48;
                }
            }

            if(n.charAt(i) == 'D') {
                if(n.charAt(i-1) == '0' && n.charAt(i-2) == '1') {
                    point[count++] = 20;
                }
                else {
                    point[count++] = (n.charAt(i-1)-48)*(n.charAt(i-1)-48);
                }
            }

            if(n.charAt(i) == 'T') {
                if(n.charAt(i-1) == '0' && n.charAt(i-2) == '1') {
                    point[count++] = 30;
                }
                else {
                    point[count++] = (n.charAt(i-1)-48)*(n.charAt(i-1)-48)*(n.charAt(i-1)-48);
                }
            }

            if(n.charAt(i) == '*') {
                if(count == 1) {
                    point[count-1] *= 2;
                }
                else {
                    point[count-1] *= 2;
                    point[count-2] *= 2;
                }
            }

            if(n.charAt(i) == '#') {
                point[count-1] *= -1;
            }
        }

        int sum = 0;

        for(int i=0; i<point.length; i++) {
            sum += point[i];
        }

        System.out.println(sum);

    }

}

2018/04/18 16:47

이병호

여러 코드를 보며 공부하는 중입니다.

static void Main(string[] args)
        {
            const int DartCnt = 3;
            Random random = new Random();
            int[] iScore = new int[11] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            string[] sBonus = new string[3] { "S", "D", "T" };
            string[] sOption = new string[3] { "*", "#", "" };
            string sGamerScoer = "";

            // 점수 취득
            for (int i = 0; i < DartCnt; i++)
            {
                sGamerScoer += iScore[random.Next(iScore.Length)].ToString();
                sGamerScoer += sBonus[random.Next(sBonus.Length)];
                sGamerScoer += sOption[random.Next(sOption.Length)];
            }

            int iLength = sGamerScoer.Length;   // 게임 횟수에 따른 점수의 총 자릿수 [ex 1S2D*3T# = 8]
            int iFlag = 1;  // 각 점수의 스텝 별 처리 [ex 1:점수 / 2:보너스 / 3:옵션 / 한게임당 자릿수는 2~4자리]
            int iStrPos = 0;    // 총 자릿수에서 현재 처리할 자릿수의 위치 [ex 0=1]
            int iScorePos = 0;  // 총 3개의 점수 중 보너스 처리를 위한 점수의 위치 [ex : 0=1S / 1=2D* / 2=3T#]
            int[] iSumScore = new int[DartCnt]; // 최종 점수 [0:1게임 / 1:2게임 / 2:3게임]

            // 1. 총 점수의 길이 만큼 반복
            while (iStrPos < iLength)
            {
                string sTarget = sGamerScoer.Substring(iStrPos, 1);

                if (iFlag == 1)
                {
                    try
                    {
                        // 1.1 첫번째 자리 점수 처리 [0~10]
                        iSumScore[iScorePos] = int.Parse(sTarget);
                        iFlag++;
                    }
                    catch (Exception ex)
                    {
                        // 1.3 옵션 처리
                        if ("*".Equals(sTarget))
                        {
                            iSumScore[iScorePos - 1] = iSumScore[iScorePos - 1] * 2;    // 해당 점수의 두배처리
                            if (iScorePos > 1) { iSumScore[iScorePos - 2] = iSumScore[iScorePos - 2] * 2; } // 첫번째 점수가 아닌 점수에서 옵션일 경우 이전 점수들도 두배처리
                        }
                        else if ("#".Equals(sTarget)) // 현재 점수의 -처리
                        {
                            iSumScore[iScorePos - 1] = iSumScore[iScorePos - 1] * (-1);
                        }
                        else { Console.WriteLine("입력점수 이상"); }
                    }
                }
                else if (iFlag == 2)
                {
                    // 1.2 보너스 처리 또는 두번째 자릿수 처리
                    if ("S".Equals(sTarget)) { iSumScore[iScorePos] = (int)Math.Pow(iSumScore[iScorePos], 1); } // 1제곱
                    else if ("D".Equals(sTarget)) { iSumScore[iScorePos] = (int)Math.Pow(iSumScore[iScorePos], 2); } // 2제곱
                    else if ("T".Equals(sTarget)) { iSumScore[iScorePos] = (int)Math.Pow(iSumScore[iScorePos], 3); } // 3제곱
                    else if ("0".Equals(sTarget))
                    {
                        if (iSumScore[iScorePos] == 1)
                        {
                            iSumScore[iScorePos] = 10; // 점수가 2자리인 경우 그 점수는 10
                            iScorePos--;    // 보너스 처리를 다시해야하기 때문에 점수의 위치 되돌림
                            iFlag++;    // 보너스 처리할 옵션이 있는지 재처리
                        }
                    }
                    else { Console.WriteLine("입력점수 이상"); }

                    // 다음 점수 처리를 위한 Flag 변경
                    iScorePos++;
                    iFlag--;
                }
                iStrPos++; // 해당 점수의 다음 문자 처리
            }
            Console.WriteLine("Dart Score {0} : {1}", sGamerScoer, iSumScore[0] + iSumScore[1] + iSumScore[2]);

            Console.ReadKey();
        }

2018/04/26 16:48

비트에이스

#include<iostream>
#include<cmath>
#include<string>
using namespace std;

void extract_num(const string str,int& branch, int &num,int sp,bool &prize_star,bool &prize_sharp)
{
    char copy[10];
    for (int i=branch; i < str.size(); i++)
    {
        if (str[i] == 'S'|| str[i] == 'D'|| str[i] == 'T')
        {
            int j = 0;
            for (int j = 0; j < i-sp; j++)
                copy[j] = str[branch++];
            num=atoi(copy);
            if (str[i] == 'D')
                num=pow(num, 2);
            else if (str[i] == 'T')
                num=pow(num, 3);
            if (str[i + 1] == '*')
                prize_star = true,branch++;
            else if (str[i + 1] == '#')
                prize_sharp = true,branch++;
            branch++;
            break;
        }
    }
}
int main()
{
    string str;
    int score[3], branch = 0;
    cout << "Input:";
    cin >> str;
    cout << "result";
    for (int i = 0; i < 3; i++)
    {
        bool prize_star = false, prize_sharp = false;
        extract_num(str, branch, score[i], branch, prize_star, prize_sharp);
        if (prize_star)
        {
            if (i == 0)
                score[i] *= 2;
            else
                score[i - 1] *= 2, score[i] *= 2;
        }
        if (prize_sharp)
            score[i] = -score[i];
    }
    int result = score[0] + score[1] + score[2];
    cout << result;

}

//더러운 코드 죄송합니다.

2018/05/14 21:19

Hujinsu

def Glosbe(a):
     domain = {'S' : 1, 'D' : 2, 'T' : 3}
     option = {'*' : 2, '#' : -1}
     Score,z,y = [],0,0
     for x in a:
          if x in domain:
               Score.append(int(a[z:y]) ** domain[x])
               z = y + 1
          elif x in option:
               b = len(Score)-1
               if x == '*' and b > 0:
                    Score[b-1] *= option[x]
                    Score[b] *= option[x]
               else:
                    Score[b] *= option[x]
               z = y + 1
          y += 1
     print(sum(i for i in Score))

2018/06/19 21:52

김영성

def ans(d):
    v1 = {'S':'**1','D':'**2','T':'**3'}
    flag = 0
    tmp = []
    for i in range(len(d)):
        if d[i] in v1:
            tmp.append('+'+d[flag:i]+v1[d[i]])
            flag = i+1
        elif d[i] == '*':
            tmp[-1] += '*2'
            if len(tmp) > 1: tmp[-2] += '*2'
            flag = i+1
        elif d[i] == '#':
            tmp[-1] += '*(-1)'
            flag = i+1

    return eval(''.join(tmp))

dartResult = ['1S2D*3T','1D2S#10S','1D2S0T','1S*2T*3S','1D#2S*3S','1T2D3D#','1D2S3T*']
print(list(map(ans,dartResult)))

[37, 9, 3, 23, 5, -4, 59]

2018/07/04 06:51

Creator

import java.util.StringTokenizer;

public class Javatutorial {
    public static int eval(String s) {
        StringTokenizer st = new StringTokenizer(s, "SDT*#", true);
        int[] arr = new int[s.length() / 2];
        int l = 0;

        while (st.hasMoreTokens()) {
            String tk = st.nextToken();
            switch (tk) {
            case "S":
                break;

            case "D":
                arr[l - 1] = arr[l - 1] * arr[l - 1];
                break;

            case "T":
                arr[l - 1] = arr[l - 1] * arr[l - 1] * arr[l - 1];
                break;

            case "*":
                arr[l - 1] *= 2;
                if (l >= 2) 
                    arr[l - 2] *= 2;
                break;

            case "#":
                arr[l - 1] *= -1;
                break;

            default:
                arr[l] = Integer.parseInt(tk);
                l++;
            }
        }

        int sum = 0;
        for (int i = 0; i < l; i++) {
            sum += arr[i];
        }

        return sum;
    }

    public static void main(String[] args) {
        String[] inputStr = {"1S2D*3T", "1D2S#10S", "1D2S0T", "1S*2T*3S", "1D#2S*3S", "1T2D3D#", "1D2S3T*"};

        for (String str : inputStr) {
            System.out.println(eval(str));
        }
    }
}

2018/07/13 02:52

Noname

Swift 입니다. 더 좋은 방법이 있다면 말씀 해주세요.

class Question2 {
// 2. 다트 게임(난이도: 하)

  static func execute(_ param: String ) -> Int {
    let count = 3

    let numbers = param.components(separatedBy: CharacterSet.decimalDigits.inverted).filter{$0 != ""}.map{ Int($0)! }

    let operators = param.components(separatedBy: CharacterSet.decimalDigits).filter{$0 != ""}

    var result = [Int]()
    for i in 0..<count {
      let opt = operators[i].lowercased()

      switch opt {
      case _ where opt.contains("s"):
        let data = numbers[i]
        result.append(data)
      case _ where opt.contains("d"):
        let data = numbers[i] * numbers[i]
        result.append(data)
      case _ where opt.contains("t"):
        let data = numbers[i] * numbers[i] * numbers[i]
        result.append(data)

      default:
        print(result)
      }

      if opt.contains("*"){
        if i != 0 {
          result[i] = 2 * result[i]
          result[i-1] = 2 * result[i-1]
        } else {
          result[i] = 2 * result[i]
        }
      } else if opt.contains("#"){
        result[i] = -1 * result[i]
      }
    }
    return result.reduce(0){$0 + $1}
  }

  static func test01() -> Bool{
     return execute("1s2d*3t") == 37
  }

  static func test02() -> Bool{
    return execute("1d2s#10s") == 9
  }

  static func test03() -> Bool{
    return execute("1d2s0t") == 3
  }

  static func test04() -> Bool{
    return execute("1s*2t*3s") == 23
  }

  static func test05() -> Bool{
    return execute("1d#2s*3s") == 5
  }

  static func test06() -> Bool{
    return  execute("1t2d3d#") == -4
  }

  static func test07() -> Bool{
    return  execute("1d2s3t*") == 59
  }

  static func testAll() -> Bool{
    return test01() &&
      test02() &&
      test03() &&
      test04() &&
      test05() &&
      test06() &&
      test07()
  }
}

2018/12/13 15:42

InKwon Kim

#include <iostream>
#include <vector>
#include <string>


using namespace std;



int main(void){
    int total = 0;
    vector<int> iv;
    string sentence;
    getline(cin, sentence);
    for (int i = 0; i < sentence.length(); i++)
    {
        if (sentence[i] == 'S')
        {
            int num;
            if (i > 1 && sentence[i - 2] > '0'&&sentence[i - 2] < '9') {

                 num = (sentence[i - 2] - 48) * 10 + (sentence[i - 1]-48);
            }
            else
            {
                num = sentence[i - 1] - 48;
            }
            iv.push_back(num);

        }
        if (sentence[i] == 'D')
        {
            int num;
            if (i > 1 && sentence[i - 2] > '0'&&sentence[i - 2] < '9') {

                num = (sentence[i - 2] - 48) * 10 + (sentence[i - 1] - 48);
            }
            else
            {
                num = sentence[i - 1] - 48;
            }
            iv.push_back(num*num);
        }
        if (sentence[i] == 'T')
        {
            int num;
            if (i>1&&sentence[i - 2] > '0'&&sentence[i - 2] < '9') {
                num = (sentence[i - 2] - 48) * 10 + (sentence[i - 1] - 48);
            }
            else
            {
                num = sentence[i - 1] - 48;
            }
            iv.push_back(num*num*num);
        }
        if (sentence[i] == '*')
        {
            for (vector<int>::iterator itr = iv.begin(); itr < iv.end(); itr++)
            {
                *itr = *itr * 2;

            }

        }
        if (sentence[i] == '#')
        {
            iv[iv.size() - 1] = -iv[iv.size() - 1];

            }
        }

    for (vector<int>::iterator itr = iv.begin(); itr < iv.end(); itr++)
    {
        total += *itr;
    }
    cout << total << endl;



}

2019/01/18 20:54

김상범

import re

def dart(s):
    d = {'S' : 1, 'D' : 2, 'T' : 3}
    shots = re.findall('(\d{1,2})([SDT])([*#]?)', s)
    ans = []
    for p, b, o in shots:
        ans.append(int(p) ** d[b])
        if o == '*':
            ans[-1] *= 2
            if i: ans[-2] *= 2
        elif o == '#':
            ans[-1] *= -1

    print(sum(ans))

s = input()
dart(s)

2019/05/22 00:40

messi

dart_result = input('Dart result : ')

bonus_type = ['S', 'D', 'T']
option_type = ['*', '#']

answer_arr = []
idx = 0

bonus = ''
option = ''
base_score = None
predecimal = False
for c in dart_result:
    if c.isdecimal():
        if not predecimal and base_score is not None:
            answer_arr.append(base_score)
            idx += 1
        if predecimal:
            base_score = base_score * 10 + int(c)
        else:
            base_score = int(c)
            predecimal = True
    else:
        predecimal = False
        if c in bonus_type:
            if c == 'S':
                base_score = base_score ** 1
            elif c == 'D':
                base_score = base_score ** 2
            elif c == 'T':
                base_score = base_score ** 3
        elif c in option_type:
            if c == '*':
                base_score = base_score * 2
                if idx > 0:
                    answer_arr[idx - 1] *= 2
            elif c == '#':
                base_score = base_score * -1

answer_arr.append(base_score)
print(sum(answer_arr))

2019/06/11 14:01

임성민

package CodingDojang;
import java.util.Scanner;
public class DartGameQuiz { 
    static int ten_check(String ans, int count, int i, int[] ans_arr) {
        if(ans.charAt(i - 1) == '0' && i - 1 > 0) {
            if(ans.charAt(i - 2) == '1') {
                return ans_arr[count] = 10;
            }
            else return ans_arr[count] = (int)ans.charAt(i-1) % 48;
        }
        else return ans_arr[count] = (int)ans.charAt(i-1) % 48;
    }

    static int award_check(String ans, int count, int i, int[] ans_arr) {
        if(i + 1 < ans.length()) {
            if(count == 0) {
                if(ans.charAt(i + 1) == '*') {
                    return ans_arr[count] *= 2;
                }
                else if(ans.charAt(i + 1) == '#') {
                    return ans_arr[count] *= -1;
                }
                else return ans_arr[count];
            }

            else if(count > 0){
                if(ans.charAt(i + 1) == '*') {
                    ans_arr[count - 1] *= 2;
                    ans_arr[count] *= 2;
                    return ans_arr[count];
                }
                else if(ans.charAt(i + 1) == '#') {
                    return ans_arr[count] *= -1;
                }
                else return ans_arr[count];
            }           
        }
        else return ans_arr[count];
        return ans_arr[count];
    }   

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String ans  = scanner.nextLine();
        int[] ans_arr = new int[3];
        int result = 0, count = 0;      

        for(int i = 0; i < ans.length(); i++) {
            if(ans.charAt(i) == 'S') {
                ten_check(ans, count, i, ans_arr);              
                result = (int)Math.pow(ans_arr[count], 1);
                ans_arr[count] = result;
                award_check(ans, count, i, ans_arr);
                count++;
            }

            else if(ans.charAt(i) == 'D') {
                ten_check(ans, count, i, ans_arr);      
                result = (int)Math.pow(ans_arr[count], 2);
                ans_arr[count] = result;
                award_check(ans, count, i, ans_arr);
                count++;
            }

            else if(ans.charAt(i) == 'T') {
                ten_check(ans, count, i, ans_arr);              
                result = (int)Math.pow(ans_arr[count], 3);
                ans_arr[count] = result;
                award_check(ans, count, i, ans_arr);
                count++;
            }       
        }   
        System.out.println(ans_arr[0]+ans_arr[1]+ans_arr[2]);
    }
}

노가다성 함수를 만들어 선언하여 보았습니다 ㅇㅅㅇ...

2019/11/07 22:08

이유환

score=input("0~10의 정수와 문자 S, D, T, *, #로 구성된 문자열을 입력하십시오: ")
lst=[]
str=""
for letter in score:
    if letter.isdigit() is True:
        str+=letter
    elif letter=="S":
        lst.append(int(str)**1)
        str=""
    elif letter=="D":
        lst.append(int(str)**2)
        str=""
    elif letter=="T":
        lst.append(int(str)**3)
        str=""
    elif letter=="*":
        lst[-1]=lst[-1]*2
        if len(lst)>1:
            lst[-2]=lst[-2]*2
    elif letter=="#":
        lst[-1]=lst[-1]*(-1)
print(sum(lst))

2020/02/14 17:30

박시원

파이썬 입니다.

ui_list = ['1S2D*3T','1D2S#10S','1D2S0T','1S*2T*3S','1D#2S*3S','1T2D3D#','1D2S3T*']


def get_qq(t):
    if t == 'S':
        return 1
    elif t == 'D':
        return 2
    elif t == 'T':
        return 3
    return 0

for ui in ui_list:
    ll = list(ui)
    sl = []
    sl_idx = -1
    tmp_num = 0

    for i in ll:
        if i.isdigit():
            if tmp_num != -1:
                tmp_num = tmp_num * 10 + int(i)
            else:
                tmp_num = int(i)
        elif i.isalpha():
            sl_idx += 1
            sl.append(tmp_num ** get_qq(i))
            tmp_num = -1
        elif i == '*':
            if sl_idx == 0:
                sl[sl_idx] = sl[sl_idx] * 2
            else:
                sl[sl_idx - 1] = sl[sl_idx - 1] * 2
                sl[sl_idx] = sl[sl_idx] * 2
        elif i == '#':
            sl[sl_idx] = sl[sl_idx] * -1

    print(ui + ' : ' + str(sum(sl)))

2020/03/29 01:15

뤼크

파이썬입니다.

세번 이상 또는 이하로 던지더라도 계산할 수 있도록 짜보았습니다.

def dart(x):
  left, number, power, option = x, [],[],[]
  while len(left)>0:
    num, po, op, left = analysis(left)
    number.append(num)
    power.append(po)
    option.append(op)
  print(scoreboard(number, power, option))

def analysis(x):
  import re
  p = re.compile('(\d+)([SDT])([*#]?)(.*)')
  lookup = p.findall(x)
  return int(lookup[0][0]),{'S': 1, 'D': 2, 'T': 3}[lookup[0][1]], {'*': 2, '#': -1}.get(lookup[0][2], 1), lookup[0][3]

def scoreboard(a, b, c): #number, power, option
  n, result=len(a), 0
  for i in range(0, n):
    try: 
      if c[i+1]==2: Retroact=2    
      else: Retroact=1
    except: Retroact=1
    result += (a[i]**b[i])*c[i]*Retroact
  return result


dart('1S2D*3T')

2021/01/30 22:50

박영빈

def Dart(): 
    a=input("다트결과 입력 : ")
    a=list(a)   
    for j in range(len(a)):
        if a[j]=='S' or a[j]=='D' or a[j]=='T' or a[j]=='#' or a[j]=='*':
            pass
        elif a[j]=='1' and a[j+1]=='0':
            a[j]='10'
            a[j+1]='1'
    dic = {'S':1, 'D':2, 'T':3, '#':-1,'*':2}
    total = 1
    n=[]
    p=[]
    for i in range(len(a)):
        if a[i]=='S' or a[i]=='D' or a[i]=='T':
            total**=dic[a[i]]
            if i<=len(a)-2 and a[i+1]=='#' :
                total*=-1
                n.append(total)
                total=1
            else:
                n.append(total)
                total=1
        elif a[i]=='#':
            pass
        elif a[i]!='*':           # 문자열로 된 숫자면 가능
            total*=int(a[i])
        elif a[i]=="*":
            t = a.index(a[i])
            a[i]=1
            p.append(t)
    if len(p)==3:
        n[0]*=4
        n[1]*=4
        n[2]*=2
    elif len(p)==2:
        if p[0]==2 and p[1]==5:
            n[0]*=4
            n[1]*=2
        elif p[0]==2 and p[1]==7:
            n[0]*=2
            n[1]*=2
            n[2]*=2
        elif p[0]==4 and p[1]==7:
            n[0]*=2
            n[1]*=4
            n[2]*=2
    elif len(p)==1:
        if p[0]==2:
            n[0]*=2
        elif p[0]==4 or p[0]==5:
            n[0]*=2
            n[1]*=2
        elif p[0]==6 or p[0]==7:
            n[1]*=2
            n[2]*=2
    print(sum(n))

Dart()

2021/04/08 18:05

fox.j

def dart_game(a):
    a = a.replace('10','x')

    list = [i for i in a]

    list[a.find('x')] = '10'


    score = []
    for i in range(len(list)):              
        if a[i] == 'S':
            score.append(int(list[i-1]))

        if a[i] == 'D':
            score.append(int(list[i-1])**2)

        if a[i] =='T':
            score.append(int(list[i-1])**3)

        if a[i] =='#':
            if i == 2:
                score[0] = score[0] * -1
            elif i == 4 or i ==5 :
                score[1] = score[1] * -1
            elif i == 6 or i ==7 or i ==8 :
                score[2] = score[2] * -1


        if a[i] =='*':
            if i == 5 :
                if list[2] == '#':
                    score[0] = score[0] * 2
                    score[1] = score[1] * 2 
                else:
                    score[0] = score[0] * 4
                    score[1] = score[1] * 2 

            elif i == 6:
                score[1] = score[1] * 2
                score[2] = score[2] * 2 

            elif i == 7:
                if list[2] =='#':
                    score[1] = score[1] * 2
                    score[2] = score[2] * 2
                elif list[4] =='#':
                    score[1] = score[1] * 2
                    score[2] = score[2] * 2
                elif list[2] == '*':
                    score[0] = score[0] * 2
                    score[1] = score[1] * 2
                    score[2] = score[2] * 2
                elif list[4] == '*':
                    score[0] = score[0] * 2
                    score[1] = score[1] * 4
                    score[2] = score[2] * 2               

            elif i == 4:
                score[0] = score[0] * 2
                score[1] = score[1] * 2



            elif i == 8:
                score[0] = score[0] * 2 * 2
                score[1] = score[1] * 2 * 2
                score[2] = score[2] * 2 
    return sum(score) 

2021/12/11 16:57

황성민

목록으로