aoc2021/Sources/01/01.swift

77 lines
2.1 KiB
Swift
Raw Permalink Normal View History

2021-12-01 19:11:11 +00:00
//
// File.swift
//
//
// Created by Max Nuding on 01.12.21.
//
import Foundation
2021-12-05 10:43:02 +00:00
import Runner
2021-12-01 20:02:05 +00:00
2021-12-05 10:43:02 +00:00
struct Day01: Runnable {
2021-12-01 19:11:11 +00:00
let inputPath: String
2021-12-01 20:02:05 +00:00
2021-12-01 19:11:11 +00:00
func run() {
let input = try! String(contentsOfFile: inputPath)
2021-12-01 20:02:05 +00:00
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)
}
2021-12-01 19:11:11 +00:00
print(measurements.currentCount)
}
2021-12-01 20:02:05 +00:00
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)
}
2021-12-01 19:11:11 +00:00
}