DEV Community

vc7
vc7

Posted on

Day 3: Mull It Over | Advent of Code 2024 | Swift | 中文

題目


第一部分

今天的題目可以用正規表示式,根據提議可以分兩層

  1. 先找出 mul(數字,數字) ,而數字為 1~3 位數
    • 正規表示式: mul\(\d{1,3},\d{1,3}\)
  2. 將找出來的字串,再吻合出兩個數字
    • 正規表示式: \d{1,3}
  3. 把兩個數字相乘
  4. 把所有的乘積加總起來
func multiplications(string: String) -> Int { let basePattern = /mul\(\d{1,3},\d{1,3}\)/ let numberPattern = /\d{1,3}/ // 1. 找出 mul(數字,數字) let matches = string.matches(of: basePattern).map { String($0.output) } return matches .map { // 2., 3. 找出吻合的兩個數字並相乘 $0.matches(of: numberPattern).compactMap{ Int($0.output) }.reduce(into: 1, *=) } // 4. 加總 .reduce(into: 0, +=) } 
Enter fullscreen mode Exit fullscreen mode

第二部分

第二部分加上一個變形,當遇到 don't() 的時候,接下來的 mul 不能被加總,當遇到 do() 的時候,接下來的 mul 就都能被加總。

  1. 找出所有的 do() don't() mul(數字,數字)
    • 正規表示式: (do\(\)|don't\(\)|mul\(\d{1,3},\d{1,3}\))
  2. 走訪吻合的結果
    • 設定一個可否加總的 flag 並預設為 true
    • 遇到 do() 則為 true
    • 遇到 don't() 則為 true
    • 其他預設則都是 mul(數字,數字) ,當 flag 為 true 時,就像第一部分一樣相乘後加總

func modMultiplications(string: String) -> Int { let basePattern = /(do\(\)|don't\(\)|mul\(\d{1,3},\d{1,3}\))/ let numberPattern = /\d{1,3}/ let matches = string.matches(of: basePattern).map { $0.output.0 } var flag = true var result = 0 for match in matches { if match == "do()" { flag = true } else if match == "don't()" { flag = false } else if flag { result += match.matches(of: /\d+/).compactMap { Int($0.output) }.reduce(into: 1, *=) } } return result } 
Enter fullscreen mode Exit fullscreen mode

結語

如果有寫錯或有建議請留言讓我知道。如果有找到更好的解法,我會再多發一篇補充。

Top comments (0)