From e233a21d36b0df5df989a38daf1957fff7c761f1 Mon Sep 17 00:00:00 2001 From: Max Nuding Date: Wed, 1 Dec 2021 21:02:05 +0100 Subject: [PATCH] 01b --- Sources/aoc2021/01.swift | 67 +++++++++++++++++++++++++++++++++++----- 1 file changed, 60 insertions(+), 7 deletions(-) diff --git a/Sources/aoc2021/01.swift b/Sources/aoc2021/01.swift index 817408f..34b5c1a 100644 --- a/Sources/aoc2021/01.swift +++ b/Sources/aoc2021/01.swift @@ -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 increaseBy = currentValue > partialResult.lastValue ? 1 : 0 - return (currentCount: partialResult.currentCount + increaseBy, lastValue: currentValue) - } + 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) + } }