d19
This commit is contained in:
41
day19/d19p1.swift
Normal file
41
day19/d19p1.swift
Normal file
@@ -0,0 +1,41 @@
|
||||
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]: Bool] = [:]
|
||||
func canMatch(_ pattern: [Color], _ towels: [[Color]]) -> Bool {
|
||||
if pattern.count == 0 {
|
||||
return true
|
||||
}
|
||||
if let cached = cache[pattern] {
|
||||
return cached
|
||||
}
|
||||
for towel in towels {
|
||||
if pattern.starts(with: towel) {
|
||||
if canMatch(Array(pattern[towel.count..<pattern.count]), towels) {
|
||||
cache[pattern] = true
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
cache[pattern] = false
|
||||
return false
|
||||
}
|
||||
|
||||
let (towels, patterns) = try readInput(CommandLine.arguments[1])
|
||||
print(patterns.filter { canMatch($0, towels) }.count)
|
Reference in New Issue
Block a user