32 lines
972 B
Swift
32 lines
972 B
Swift
import Foundation
|
|
|
|
typealias Color = Character
|
|
|
|
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(Array.init)
|
|
let patterns = lines[1..<lines.count].map(Array.init)
|
|
return (towels, patterns)
|
|
}
|
|
|
|
var cache: [[Color]: Bool] = [[]: true]
|
|
func canMatch(_ pattern: [Color], _ towels: [[Color]]) -> Bool {
|
|
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)
|