40 lines
1.0 KiB
Swift
40 lines
1.0 KiB
Swift
import Foundation
|
|
|
|
struct NumTimes : Hashable {
|
|
let num: Int
|
|
let times: Int
|
|
}
|
|
|
|
func readInput(_ filePath: String) throws -> [Int] {
|
|
return try String(contentsOfFile: filePath, encoding: .ascii)
|
|
.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
.split(separator: " ").map { Int($0)! }
|
|
}
|
|
|
|
func evolve(_ num: Int) -> [Int] {
|
|
if num == 0 { return [1] }
|
|
let s = String(num)
|
|
if s.count.isMultiple(of: 2) {
|
|
return [
|
|
Int(String(Array(s)[s.count/2 ..< s.count]))!,
|
|
Int(String(Array(s)[0 ..< s.count/2]))!
|
|
]
|
|
}
|
|
return [num * 2024]
|
|
|
|
}
|
|
|
|
var cache: [NumTimes: Int] = [:]
|
|
|
|
func count(_ num: Int, times: Int) -> Int {
|
|
if times == 0 { return 1 }
|
|
let key = NumTimes(num: num, times: times)
|
|
if let cached = cache[key] { return cached }
|
|
cache[key] = evolve(num).map { n in count(n, times: times-1) }.reduce(0, +)
|
|
return cache[key]!
|
|
}
|
|
|
|
let nums = try readInput(CommandLine.arguments[1])
|
|
print(nums)
|
|
print(nums.map { count($0, times: 75) }.reduce(0, +))
|