09a
This commit is contained in:
82
Sources/09/09.swift
Normal file
82
Sources/09/09.swift
Normal file
@ -0,0 +1,82 @@
|
||||
//
|
||||
// File.swift
|
||||
//
|
||||
//
|
||||
// Created by Max Nuding on 05.12.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Runner
|
||||
import Collections
|
||||
|
||||
struct Coord {
|
||||
let row: Int
|
||||
let col: Int
|
||||
|
||||
func getLeft() -> Coord? {
|
||||
guard col > 0 else {
|
||||
return nil
|
||||
}
|
||||
return Coord(row: row, col: col - 1)
|
||||
}
|
||||
|
||||
func getRight() -> Coord { Coord(row: row, col: col + 1) }
|
||||
|
||||
func getAbove() -> Coord? {
|
||||
guard row > 0 else {
|
||||
return nil
|
||||
}
|
||||
return Coord(row: row - 1, col: col)
|
||||
}
|
||||
|
||||
func getBelow() -> Coord { Coord(row: row + 1, col: col) }
|
||||
}
|
||||
|
||||
struct Field {
|
||||
let numbers: [[Int]]
|
||||
let numCols: Int
|
||||
let numRows: Int
|
||||
|
||||
init(numbers: [[Int]]) {
|
||||
self.numbers = numbers
|
||||
numCols = numbers.first!.count
|
||||
numRows = numbers.count
|
||||
}
|
||||
|
||||
func getNeighborsCoordsFor(coord: Coord) -> [Coord] {
|
||||
return [coord.getAbove(), coord.getRight(), coord.getBelow(), coord.getLeft()]
|
||||
.compactMap { $0 }
|
||||
.filter { $0.row < numRows && $0.col < numCols }
|
||||
}
|
||||
|
||||
func lowPointValueAt(coord: Coord) -> Int? {
|
||||
let value = numbers[coord.row][coord.col]
|
||||
return getNeighborsCoordsFor(coord: coord)
|
||||
.map { numbers[$0.row][$0.col] }
|
||||
.allSatisfy { $0 > value }
|
||||
? value
|
||||
: nil
|
||||
}
|
||||
}
|
||||
|
||||
struct Day09: Runnable {
|
||||
let inputPath: String
|
||||
|
||||
func run() {
|
||||
let input = try! String(contentsOfFile: inputPath)
|
||||
let entries = input
|
||||
.trimmingCharacters(in: .newlines)
|
||||
.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
|
||||
}
|
||||
}
|
||||
}
|
||||
print(sum)
|
||||
}
|
||||
}
|
12
Sources/09/main.swift
Normal file
12
Sources/09/main.swift
Normal file
@ -0,0 +1,12 @@
|
||||
//
|
||||
// File.swift
|
||||
//
|
||||
//
|
||||
// Created by Max Nuding on 05.12.21.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Runner
|
||||
|
||||
//Runner(target: Day09.self, day: "09", isTest: true).run()
|
||||
Runner(target: Day09.self, day: "09", isTest: false).run()
|
Reference in New Issue
Block a user