make d14p2 better

This commit is contained in:
2024-12-15 09:43:51 -08:00
parent 2218cf8661
commit b8945e61a3

View File

@@ -35,31 +35,43 @@ func readInput(_ filePath: String) throws -> [Robot] {
return robots return robots
} }
func complexity(_ input: String) -> Int { func variance(_ bots: [Robot]) -> Int {
var last: Character = " " let (sX, sY) = bots.reduce((0, 0)) { s, bot in (s.0 + bot.x, s.1 + bot.y) }
return input.reduce(0, { s, c in let (mX, mY) = (sX/bots.count, sY/bots.count)
if c != last { last = c; return s + 1 } else { return s } return bots.reduce(0) { s, bot in
}) s + (mX-bot.x)*(mX-bot.x) + (mY-bot.y)*(mY-bot.y) }
} }
func printRobots(_ robots: [Robot]) -> String { func printRobots(_ bots: [Robot]) -> String {
var screen: [[String]] = Array(repeating: Array(repeating: " ", count: 101), count: 103) var screen: [[String]] = Array(
robots.forEach { robot in screen[robot.y][robot.x] = "" } repeating: Array(repeating: " ", count: 101),
count: 52
)
bots.forEach { bot in
let (q, r) = bot.y.quotientAndRemainder(dividingBy: 2)
if screen[q][bot.x] == " " {
screen[q][bot.x] = (r == 0) ? "" : ""
} else {
screen[q][bot.x] = ""
}
}
return screen.map { row in row.joined() }.joined(separator: "\n") return screen.map { row in row.joined() }.joined(separator: "\n")
} }
var bots = try readInput(CommandLine.arguments[1]) var bots = try readInput(CommandLine.arguments[1])
var i = 0 var i = 0
var minSigma = Int.max
while true { while true {
i += 1 i += 1
for i in 0..<bots.count { for i in 0..<bots.count {
bots[i].move() bots[i].move()
} }
let printout = printRobots(bots) let printout = printRobots(bots)
let cpx = complexity(printout) let sigma = variance(bots)
if cpx < 800 { if sigma < minSigma {
minSigma = sigma
//print("\u{001B}[2J")
print(printout) print(printout)
print("i=\(i) rle=\(cpx)") print("i=\(i) =\(sigma)")
break
} }
} }