d11
This commit is contained in:
39
day11/d11p2.swift
Normal file
39
day11/d11p2.swift
Normal file
@@ -0,0 +1,39 @@
|
||||
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 {
|
||||
let key = NumTimes(num: num, times: times)
|
||||
if let cached = cache[key] { return cached }
|
||||
if times == 0 { return 1 }
|
||||
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, +))
|
Reference in New Issue
Block a user