Skip to content

Instantly share code, notes, and snippets.

@timvermeulen
Last active December 11, 2018 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timvermeulen/2b1b78e38305f535e223b732a975f5e7 to your computer and use it in GitHub Desktop.
Save timvermeulen/2b1b78e38305f535e223b732a975f5e7 to your computer and use it in GitHub Desktop.
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