diff --git a/2015/Sources/AdventOfCode.swift b/2015/Sources/AdventOfCode.swift index 896eef1..7b20b1d 100644 --- a/2015/Sources/AdventOfCode.swift +++ b/2015/Sources/AdventOfCode.swift @@ -20,6 +20,7 @@ let allChallenges: [any AdventDay] = [ Day16(), Day17(), Day18(), + Day19(), ] @main diff --git a/2015/Sources/Day19.swift b/2015/Sources/Day19.swift new file mode 100644 index 0000000..ccada8a --- /dev/null +++ b/2015/Sources/Day19.swift @@ -0,0 +1,33 @@ +import Foundation + +struct Day19: AdventDay { + let data: String + + private var replacements: [String: [String]] { + data.split(separator: /\n\n/)[0] + .matches(of: /^(?'source'[A-Za-z]{1}[a-z]{,1}) => (?'replacement'[A-Za-z]+)$/.anchorsMatchLineEndings()) + .map { + (String($0.output.source), String($0.output.replacement)) + } + .reduce(into: [String:[String]]()) { result, mapping in + result[mapping.0, default: []].append(mapping.1) + } + } + private var molecole: String { + String(data.split(separator: /\n\n/)[1]) + } + + func part1() -> Int { + let all = replacements.flatMap { key, values in + values.flatMap { value in + molecole.matches(of: try! Regex(key)).map { match in + var molecole = molecole + molecole.replaceSubrange(match.range, with: value) + return molecole + } + } + }.uniqued() + + return Set(all).count + } +} diff --git a/2015/Tests/Day19Tests.swift b/2015/Tests/Day19Tests.swift new file mode 100644 index 0000000..fb50c72 --- /dev/null +++ b/2015/Tests/Day19Tests.swift @@ -0,0 +1,17 @@ +import Testing + +@testable import AoC2015 + +struct Day19Tests { + private let testData = """ + H => HO + H => OH + O => HH + + HOH + """.replacing(/( )+/.anchorsMatchLineEndings(), with: "") + + @Test func testPart1() { + #expect(Day19(data: testData).part1() == 4) + } +}