Files
aoc24/day14/d14p2.swift
2024-12-14 23:26:29 -08:00

66 lines
1.8 KiB
Swift

import Foundation
let (w, h) = (101, 103)
infix operator %%: MultiplicationPrecedence
func %%<T: BinaryInteger>(lhs: T, rhs: T) -> T {
return (lhs % rhs + rhs) % rhs
}
struct Robot : CustomStringConvertible {
var (x, y): (Int, Int)
let (vx, vy): (Int, Int)
var description: String { return "p=(\(x), \(y)) v=(\(vx), \(vy))" }
mutating func move() {
x = (x + vx) %% w
y = (y + vy) %% h
}
}
func readInput(_ filePath: String) throws -> [Robot] {
let robot = try Regex(#"p=([0-9]+),([0-9]+) v=([0-9-]+),([0-9-]+)"#)
var robots: [Robot] = []
let content = try String(contentsOfFile: filePath, encoding: .ascii)
content.split(separator: "\n").forEach { line in
if let m = line.wholeMatch(of: robot) {
robots.append(Robot(
x: Int(m.output[1].substring!)!,
y: Int(m.output[2].substring!)!,
vx: Int(m.output[3].substring!)!,
vy: Int(m.output[4].substring!)!
))
}
}
return robots
}
func complexity(_ input: String) -> Int {
var last: Character = " "
return input.reduce(0, { s, c in
if c != last { last = c; return s + 1 } else { return s }
})
}
func printRobots(_ robots: [Robot]) -> String {
var screen: [[String]] = Array(repeating: Array(repeating: " ", count: 101), count: 103)
robots.forEach { robot in screen[robot.y][robot.x] = "" }
return screen.map { row in row.joined() }.joined(separator: "\n")
}
var bots = try readInput(CommandLine.arguments[1])
var i = 0
while true {
i += 1
for i in 0..<bots.count {
bots[i].move()
}
let printout = printRobots(bots)
let cpx = complexity(printout)
if cpx < 800 {
print(printout)
print("i=\(i) rle=\(cpx)")
break
}
}