From 1ff50f072e98263f9bb489ef98a59f7052ca6e2d Mon Sep 17 00:00:00 2001 From: Max Nuding Date: Thu, 9 Dec 2021 07:48:45 +0100 Subject: [PATCH] RafaSwitched to sequence --- Sources/09/09.swift | 33 ++++++++++++++++++++++++--------- Sources/09/main.swift | 4 ++-- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/Sources/09/09.swift b/Sources/09/09.swift index fb01a62..89662d5 100644 --- a/Sources/09/09.swift +++ b/Sources/09/09.swift @@ -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..