make d19p2 shorter

This commit is contained in:
2024-12-19 08:42:56 -08:00
parent 3057dfabac
commit 4c57a82818

View File

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