This commit is contained in:
Max Nuding 2021-12-01 21:02:05 +01:00
parent bdc7895a61
commit e233a21d36
Signed by: phlaym
GPG Key ID: A06651BAB6777237

View File

@ -6,17 +6,70 @@
//
import Foundation
struct Day01 {
let inputPath: String
func run() {
let input = try! String(contentsOfFile: inputPath)
let measurements = input
.split(separator: "\n")
.compactMap { Int32($0) }
.reduce((currentCount: 0, lastValue: Int32.max)) { partialResult, currentValue in
let distances = input
.components(separatedBy: .newlines)
.compactMap { Int($0) }
runA(distances: distances)
runB(distances: distances)
}
func runA(distances: [Int]) {
let measurements = distances.reduce((currentCount: 0, lastValue: Int.max)) { partialResult, currentValue in
let increaseBy = currentValue > partialResult.lastValue ? 1 : 0
return (currentCount: partialResult.currentCount + increaseBy, lastValue: currentValue)
}
print(measurements.currentCount)
}
func runB(distances: [Int]) {
// Sliding window would've been better, but I was too tired to bend reduce to my will. Oh well!
var arrA = [Int]()
var arrB = [Int]()
var arrC = [Int]()
var sumA = Int.max
var sumB = Int.max
var sumC = Int.max
var increases = 0
for (idx, distance) in distances.enumerated() {
arrA.append(distance)
if idx == 0 {
continue
}
arrB.append(distance)
if idx == 1 {
continue
}
arrC.append(distance)
if arrA.count == 3 {
sumA = arrA.reduce(0, +)
arrA = [Int]()
if sumA > sumC {
increases += 1
}
}
if arrB.count == 3 {
sumB = arrB.reduce(0, +)
arrB = [Int]()
if sumB > sumA {
increases += 1
}
}
if arrC.count == 3 {
sumC = arrC.reduce(0, +)
arrC = [Int]()
if sumC > sumB {
increases += 1
}
}
}
print(increases)
}
}