This commit is contained in:
2024-12-18 22:22:02 -08:00
parent a785612ad1
commit 3057dfabac
4 changed files with 490 additions and 0 deletions

37
day19/d19p2.swift Normal file
View File

@@ -0,0 +1,37 @@
import Foundation
enum Color: Character, CustomStringConvertible {
case r = "r"
case g = "g"
case u = "u"
case w = "w"
case b = "b"
var description: String { return String(self.rawValue) }
}
func readInput(_ filePath: String) throws -> ([[Color]], [[Color]]) {
let content = try String(contentsOfFile: filePath, encoding: .ascii)
let lines = content.split(separator: "\n")
let towels = lines[0].split(separator: ", ").map { $0.compactMap(Color.init) }
let patterns = lines[1..<lines.count].map { $0.compactMap(Color.init) }
return (towels, patterns)
}
var cache: [[Color]: Int] = [:]
func matches(_ pattern: [Color], _ towels: [[Color]]) -> Int {
if pattern.count == 0 {
return 1
}
if let cached = cache[pattern] {
return cached
}
let r = towels
.filter { pattern.starts(with: $0) }
.map { matches(Array(pattern[$0.count..<pattern.count]), towels) }
.reduce(0, +)
cache[pattern] = r
return r
}
let (towels, patterns) = try readInput(CommandLine.arguments[1])
print(patterns.reduce(0) { s, p in s + matches(p, towels) })