From 93f1c73fbf56dd670c4693c60ebe6a61ddeda858 Mon Sep 17 00:00:00 2001 From: Max Nuding Date: Thu, 9 Dec 2021 20:01:26 +0100 Subject: [PATCH] Caching neighbours --- Sources/09/09.swift | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Sources/09/09.swift b/Sources/09/09.swift index 18fe9bd..055cf8c 100644 --- a/Sources/09/09.swift +++ b/Sources/09/09.swift @@ -38,6 +38,8 @@ struct Field:Sequence, IteratorProtocol { let numCols: Int let numRows: Int + var neighbors = [Coord:[Coord]]() + var current: Coord? = Coord(row: 0, col: 0) init(numbers: [[Int]]) { @@ -46,13 +48,15 @@ struct Field:Sequence, IteratorProtocol { numRows = numbers.count } - func getNeighborsCoordsFor(coord: Coord) -> [Coord] { - return [coord.getAbove(), coord.getRight(), coord.getBelow(), coord.getLeft()] + mutating func getNeighborsCoordsFor(coord: Coord) -> [Coord] { + let n = neighbors[coord] ?? [coord.getAbove(), coord.getRight(), coord.getBelow(), coord.getLeft()] .compactMap { $0 } .filter { $0.row < numRows && $0.col < numCols } + neighbors[coord] = n + return n } - func isLowPointAt(coord: Coord) -> Bool { + mutating func isLowPointAt(coord: Coord) -> Bool { let value = self[coord] return getNeighborsCoordsFor(coord: coord) .map { numbers[$0.row][$0.col] }