aoc2021/Sources/01/01.swift
2021-12-05 11:43:49 +01:00

77 lines
2.1 KiB
Swift

//
// File.swift
//
//
// Created by Max Nuding on 01.12.21.
//
import Foundation
import Runner
struct Day01: Runnable {
let inputPath: String
func run() {
let input = try! String(contentsOfFile: inputPath)
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)
}
}