Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Algorithm] [1차] 다트 게임 #69

Closed
hwangJi-dev opened this issue Jan 14, 2023 · 0 comments
Closed

[Algorithm] [1차] 다트 게임 #69

hwangJi-dev opened this issue Jan 14, 2023 · 0 comments

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Jan 14, 2023

💬 문제

[프로그래머스](https://school.programmers.co.kr/learn/courses/30/lessons/17682/solution_groups?language=swift)


💬 Idea

  • “S”, “D”, “T”, “#”, “*”가 나올 때마다 cutIndex를 +해주고,
    • “S”, “D”, “T”가 나오면 cutIndex부터 Index까지 잘라서 정수를 빼내준 뒤 num 배열에 append한다.
      → 10을 문자열로 다루면 1, 0으로 잘리기 때문에 이렇게 잘라주는 것이다!

💬 풀이

func solution(dartResult:String) -> Int {
    let dict = ["S": 1, "D": 2, "T": 3]
    let str: [String] = Array(dartResult).map({ String($0) })
    var num: [Int] = []
    var cutIndex = 0
    
    for (index, i) in dartResult.enumerated() {
        if dartResult.filter({ !$0.isNumber }).contains(i) {
            let n = str[cutIndex..<index].joined()
            if n != "" {
                num.append(Int(n)!)
            }
            cutIndex = index + 1
            
            if i == "S" || i == "D" || i == "T" {
                num[num.count - 1] = Int(pow(Double(num[num.count - 1]), Double(dict[String(i)]!)))
            } else if i == "*" {
                num[num.count - 1] *= 2
                if num.count - 2 >= 0 {
                    num[num.count - 2] *= 2
                }
            } else {
                num[num.count - 1] *= -1
            }
        }
    }

    return num.reduce(0, +)
}
func solution(dartResult:String) -> Int {
    let dict = ["S": 1, "D": 2, "T": 3]
    let str: [String] = Array(dartResult).map({ String($0) })
    var num: [Int] = []
    var cutIndex = 0
    
    for (index, i) in dartResult.enumerated() {
        switch i {
        case "S", "D", "T":
            num.append(Int(str[cutIndex..<index].joined()) ?? 0)
            num[num.count - 1] = Int(pow(Double(num[num.count - 1]), Double(dict[String(i)]!)))
            cutIndex = index + 1
        case "*":
            num[num.count - 1] *= 2
            if num.count - 2 >= 0 {
                num[num.count - 2] *= 2
            }
            cutIndex = index + 1
        case "#":
            num[num.count - 1] *= -1
            cutIndex = index + 1
        default:
            break
        }
    }

    return num.reduce(0, +)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant