aoc2021/Sources/07/07.swift

49 lines
1.7 KiB
Swift

//
// File.swift
//
//
// Created by Max Nuding on 05.12.21.
//
import Foundation
import Runner
struct Day07: Runnable {
let inputPath: String
func run() {
let input = try! String(contentsOfFile: inputPath)
let horizontalPositions = input
.trimmingCharacters(in: .newlines)
.components(separatedBy: ",")
.map { Int($0)! }
runA(horizontalPositions: horizontalPositions)
runB(horizontalPositions: horizontalPositions)
}
func runA(horizontalPositions: [Int]) {
let median = horizontalPositions.sorted()[horizontalPositions.count / 2]
let distancesToMedian = horizontalPositions.map { abs(median - $0) }
let toalFuel = distancesToMedian.reduce(0,+)
print(toalFuel)
}
func runB(horizontalPositions: [Int]) {
let average = Double(horizontalPositions.reduce(0, +)) / Double(horizontalPositions.count)
let roundedDown = Int(average.rounded(.up))
let roundedUp = Int(average.rounded(.down))
let fuelForRoundedDown = fuelConsumptionFor(horizontalPositions: horizontalPositions, toPosition: roundedDown)
let fuelForRoundedUp = fuelConsumptionFor(horizontalPositions: horizontalPositions, toPosition: roundedUp)
print(min(fuelForRoundedDown, fuelForRoundedUp))
}
func fuelConsumptionFor(horizontalPositions: [Int], toPosition targetPos: Int) -> Int {
horizontalPositions.map { fuelConsumptionFor(numSteps: abs(targetPos - $0)) }.reduce(0,+)
}
func fuelConsumptionFor(numSteps: Int) -> Int {
let dv = Double(numSteps)
return Int((pow(dv, 2) + dv) / 2.0)
}
}