d11
This commit is contained in:
62
day11/d11p1.swift
Normal file
62
day11/d11p1.swift
Normal file
@@ -0,0 +1,62 @@
|
||||
import Foundation
|
||||
|
||||
class Node : CustomStringConvertible {
|
||||
var value: Int
|
||||
var next: Node?
|
||||
init(_ value: Int, next: Node? = nil) {
|
||||
self.value = value
|
||||
self.next = next
|
||||
}
|
||||
var description: String {
|
||||
let nextStr = if let next { String(describing: next) } else { "nil" }
|
||||
return "(\(value))->\(nextStr)"
|
||||
}
|
||||
func evolve() -> Int {
|
||||
if value == 0 {
|
||||
value = 1
|
||||
return 1
|
||||
}
|
||||
// I don't have log10() unless I import Graphics, which is overkill...
|
||||
let s = String(value)
|
||||
if s.count.isMultiple(of: 2) {
|
||||
let secondHalf = s.count/2 ..< s.count
|
||||
let newNode = Node(Int(String(Array(s)[secondHalf]))!, next: next)
|
||||
value = Int(String(Array(s)[0 ..< s.count/2]))!
|
||||
next = newNode
|
||||
return 2
|
||||
}
|
||||
value = value*2024
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
func readInput(_ filePath: String) throws -> Node {
|
||||
let content = try String(contentsOfFile: filePath, encoding: .ascii)
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let head: Node = Node(-1)
|
||||
var current = head
|
||||
content.split(separator: " ").forEach { i in
|
||||
print(i)
|
||||
let new = Node(Int(i)!)
|
||||
current.next = new
|
||||
current = new
|
||||
}
|
||||
return head.next!
|
||||
}
|
||||
|
||||
func evolve(_ chain: Node) -> Int {
|
||||
var next: Node? = chain
|
||||
var count = 0
|
||||
while let node = next {
|
||||
next = node.next
|
||||
count += node.evolve()
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
let nums = try readInput(CommandLine.arguments[1])
|
||||
print(nums)
|
||||
for i in 1...25 {
|
||||
let count = evolve(nums)
|
||||
print("\(i): \(count)") // - \(nums)")
|
||||
}
|
Reference in New Issue
Block a user