RafaSwitched to sequence

This commit is contained in:
Max Nuding 2021-12-09 07:48:45 +01:00
parent c6e3288cb8
commit 1ff50f072e
Signed by: phlaym
GPG Key ID: A06651BAB6777237
2 changed files with 26 additions and 11 deletions

View File

@ -32,11 +32,13 @@ struct Coord {
func getBelow() -> Coord { Coord(row: row + 1, col: col) }
}
struct Field {
struct Field:Sequence, IteratorProtocol {
let numbers: [[Int]]
let numCols: Int
let numRows: Int
var current: Coord? = Coord(row: 0, col: 0)
init(numbers: [[Int]]) {
self.numbers = numbers
numCols = numbers.first!.count
@ -57,6 +59,26 @@ struct Field {
? value
: nil
}
private func getNextCoord() -> Coord? {
guard let current = current else {
return nil
}
if current.col == numCols - 1 && current.row == numRows - 1 {
return nil
}
if current.col == numCols - 1 {
return Coord(row: current.row + 1, col: 0)
}
return Coord(row: current.row, col: current.col + 1)
}
mutating func next() -> Coord? {
defer {
current = getNextCoord()
}
return current
}
}
struct Day09: Runnable {
@ -69,14 +91,7 @@ struct Day09: Runnable {
.components(separatedBy: .newlines)
.map { line in line.map { $0.wholeNumberValue! } }
let field = Field(numbers: entries)
var sum = 0
for row in 0..<field.numRows {
for col in 0..<field.numCols {
if let lpv = field.lowPointValueAt(coord: Coord(row: row, col: col)) {
sum += lpv + 1
}
}
}
let sum = field.compactMap { field.lowPointValueAt(coord: $0) }.reduce(0, { $0 + $1 + 1 })
print(sum)
}
}

View File

@ -8,5 +8,5 @@
import Foundation
import Runner
//Runner(target: Day09.self, day: "09", isTest: true).run()
Runner(target: Day09.self, day: "09", isTest: false).run()
Runner(target: Day09.self, day: "09", isTest: true).run()
//Runner(target: Day09.self, day: "09", isTest: false).run()