52 lines
1.5 KiB
Swift
52 lines
1.5 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
|
|
}
|
|
|
|
var robots = try readInput(CommandLine.arguments[1])
|
|
for _ in 0..<100 {
|
|
for i in 0..<robots.count {
|
|
robots[i].move()
|
|
}
|
|
}
|
|
var (ul, ur, ll, lr) = (0, 0, 0, 0)
|
|
for robot in robots {
|
|
if robot.x < w/2 && robot.y < h/2 { ul += 1 }
|
|
if robot.x > w/2 && robot.y < h/2 { ur += 1 }
|
|
if robot.x < w/2 && robot.y > h/2 { ll += 1 }
|
|
if robot.x > w/2 && robot.y > h/2 { lr += 1 }
|
|
}
|
|
print("\(ul) x \(ur) x \(ll) x \(lr) = \(ul * ur * ll * lr)")
|