25 lines
871 B
Swift
25 lines
871 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 knowns: [[Color]: Int] = [[]: 1]
|
|
func matches(_ pattern: [Color], _ towels: [[Color]]) -> Int {
|
|
if let cached = knowns[pattern] { return cached }
|
|
knowns[pattern] = towels
|
|
.filter { pattern.starts(with: $0) }
|
|
.map { matches(Array(pattern[$0.count..<pattern.count]), towels) }
|
|
.reduce(0, +)
|
|
return knowns[pattern]!
|
|
}
|
|
|
|
let (towels, patterns) = try readInput(CommandLine.arguments[1])
|
|
print(patterns.map{ matches($0, towels) }.reduce(0, +))
|