Skip to content

Instantly share code, notes, and snippets.

@macshome
Last active December 4, 2019 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macshome/3cd5a44c1d6304ce4818696262bda98c to your computer and use it in GitHub Desktop.
Save macshome/3cd5a44c1d6304ce4818696262bda98c to your computer and use it in GitHub Desktop.
Advent of Code 2019 - Day 1
import Foundation
// Code-golf version
let inputFile = URL(fileReferenceLiteralResourceName: "input.txt")
print(try! String(contentsOf: inputFile).components(separatedBy: .newlines).compactMap { Float($0) }.map { Int(($0 / 3).rounded(.down) - 2) }.reduce(0, +))
// Fancy version
typealias ModuleHopper = [Module]
typealias MassCalculations = [Float]
struct Module {
let mass: Float
let fuel: Int
init(withMass mass: Float) {
self.mass = mass
self.fuel = Int((mass / 3).rounded(.down) - 2)
}
}
func loadInput() throws -> MassCalculations {
do {
let inputFile = URL(fileReferenceLiteralResourceName: "input.txt")
let rawInput = try String(contentsOf: inputFile)
let splitFile = rawInput.components(separatedBy: .newlines)
return splitFile.compactMap { Float($0) }
} catch {
throw error
}
}
func calculateModules(from mass: MassCalculations) -> ModuleHopper {
return mass.map { Module(withMass: $0) }
}
func calculateFuel(_ modules: ModuleHopper) -> Int {
return modules.reduce(0, { $0 + $1.fuel })
}
func fuelCounterUpper() throws -> Int {
do {
let masses = try loadInput()
let modules = calculateModules(from: masses)
return calculateFuel(modules)
} catch {
throw error
}
}
if let fuelNeeded = try? fuelCounterUpper() {
print("Total fuel units required: \(fuelNeeded)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment