aoc2021/Sources/07/07.swift
2021-12-07 07:26:59 +01:00

49 lines
1.6 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(floor(average))
let roundedUp = Int(ceil(average))
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)
}
}