Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
let totalSize = 300
func powerLevel(x: Int, y: Int, serialNumber: Int) -> Int {
let rackID = x + 10
return ((rackID * y + serialNumber) * rackID / 100) % 10 - 5
}
func part2(serialNumber: Int) -> String {
let grid = (1...totalSize).map { y in
(1...totalSize).map { x in
powerLevel(x: x, y: y, serialNumber: serialNumber)
}
}
let partialX = grid.map { $0.scan(0, +) }
let partial = (0..<totalSize).map { x in partialX.lazy.map { $0[x] }.scan(0, +) }
var maxSum = Int.min
var solution: (x: Int, y: Int, size: Int)!
for size in 1...totalSize {
for x in 0..<(totalSize - size) {
for y in 0..<(totalSize - size) {
let sum = partial[x + size][y + size]
- partial[x][y + size]
- partial[x + size][y]
+ partial[x][y]
if sum > maxSum {
maxSum = sum
solution = (x + 1, y + 1, size)
}
}
}
}
return "\(solution.x),\(solution.y),\(solution.size)"
}
extension Sequence {
func scan<T>(_ initial: T, _ next: (T, Element) -> T) -> [T] {
var result = [initial]
var last = initial
for element in self {
last = next(last, element)
result.append(last)
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment