diff --git a/Sources/14/14.swift b/Sources/14/14.swift index ed236be..9b6a502 100644 --- a/Sources/14/14.swift +++ b/Sources/14/14.swift @@ -33,42 +33,49 @@ class Day14: Runnable { let parts = input .trimmingCharacters(in: .newlines) .components(separatedBy: "\n\n") - var startingPolymer = parts.first! + let startingPolymer = parts.first! let replacements = parts.last! .components(separatedBy: .newlines) - .map(Replacement.init) + .map {$0.components(separatedBy: " -> ")} + .reduce(into: [String:String](), { p, c in + p[c.first!] = c.last! + }) - for step in 1...10 { - var inserts = [(String.Index, Character)]() - for i in startingPolymer.indices { - let next = startingPolymer.index(i, offsetBy: 1) - guard next != startingPolymer.endIndex else { - continue - } - var pair = startingPolymer[i]/* + startingPolymer[next]*/ - let p = "\(startingPolymer[i])\(startingPolymer[next])" - for replacement in replacements { - if let c = replacement.replace(pair: p) { - inserts.append((next, c)) - break - } - } + var pairCounts = [String:Int]() + for i in startingPolymer.indices { + let next = startingPolymer.index(i, offsetBy: 1) + guard next != startingPolymer.endIndex else { + continue } - - var tmp = startingPolymer - var count = 0 - for r in inserts { - let idx = tmp.index(r.0, offsetBy: count) - tmp.insert(r.1, at: idx) - count += 1 - } - startingPolymer = tmp + let pair = "\(startingPolymer[i])\(startingPolymer[next])" + pairCounts[pair, default: 0] += 1 } - let charCounts = startingPolymer.reduce(into: [String.Element: Int](), { + var charCount = startingPolymer.reduce(into: [String.Element:Int](), { $0[$1, default: 0] += 1 }) - let maxC = charCounts.max(by: {$0.value < $1.value })! - let minC = charCounts.min(by: {$0.value < $1.value })! + + for step in 1...40 { + let tmpPairCounts = pairCounts + for pairCount in tmpPairCounts { + let pair = pairCount.key + let replacement = replacements[pair]! + pairCounts[pair]! -= pairCount.value + let firstCharacter = pair.first! + let secondCharacter = pair.last! + pairCounts["\(firstCharacter)\(replacement)", default: 0] += pairCount.value + pairCounts["\(replacement)\(secondCharacter)", default: 0] += pairCount.value + charCount[replacement.first!, default: 0] += pairCount.value + } + if step == 10 { + printResult(charCount: charCount) + } + } + printResult(charCount: charCount) + } + + func printResult(charCount: [String.Element:Int]) { + let maxC = charCount.max(by: {$0.value < $1.value })! + let minC = charCount.min(by: {$0.value < $1.value })! print(maxC.value - minC.value) } }