2021-12-07 06:10:31 +00:00
|
|
|
//
|
|
|
|
// 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)! }
|
2021-12-07 06:26:59 +00:00
|
|
|
runA(horizontalPositions: horizontalPositions)
|
|
|
|
runB(horizontalPositions: horizontalPositions)
|
2021-12-07 06:10:31 +00:00
|
|
|
}
|
|
|
|
|
2021-12-07 06:26:59 +00:00
|
|
|
func runA(horizontalPositions: [Int]) {
|
2021-12-07 06:10:31 +00:00
|
|
|
let median = horizontalPositions.sorted()[horizontalPositions.count / 2]
|
|
|
|
let distancesToMedian = horizontalPositions.map { abs(median - $0) }
|
|
|
|
let toalFuel = distancesToMedian.reduce(0,+)
|
|
|
|
print(toalFuel)
|
|
|
|
}
|
2021-12-07 06:26:59 +00:00
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
2021-12-07 06:10:31 +00:00
|
|
|
}
|