make d14p2 better
This commit is contained in:
@@ -35,31 +35,43 @@ func readInput(_ filePath: String) throws -> [Robot] {
|
||||
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 variance(_ bots: [Robot]) -> Int {
|
||||
let (sX, sY) = bots.reduce((0, 0)) { s, bot in (s.0 + bot.x, s.1 + bot.y) }
|
||||
let (mX, mY) = (sX/bots.count, sY/bots.count)
|
||||
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 {
|
||||
var screen: [[String]] = Array(repeating: Array(repeating: " ", count: 101), count: 103)
|
||||
robots.forEach { robot in screen[robot.y][robot.x] = "█" }
|
||||
func printRobots(_ bots: [Robot]) -> String {
|
||||
var screen: [[String]] = Array(
|
||||
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")
|
||||
}
|
||||
|
||||
var bots = try readInput(CommandLine.arguments[1])
|
||||
var i = 0
|
||||
var minSigma = Int.max
|
||||
while true {
|
||||
i += 1
|
||||
for i in 0..<bots.count {
|
||||
bots[i].move()
|
||||
}
|
||||
let printout = printRobots(bots)
|
||||
let cpx = complexity(printout)
|
||||
if cpx < 800 {
|
||||
let sigma = variance(bots)
|
||||
if sigma < minSigma {
|
||||
minSigma = sigma
|
||||
//print("\u{001B}[2J")
|
||||
print(printout)
|
||||
print("i=\(i) rle=\(cpx)")
|
||||
break
|
||||
print("i=\(i) s²=\(sigma)")
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user