Skip to content

Instantly share code, notes, and snippets.

@groob
Created December 2, 2019 03:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save groob/cc4b4cca4937e4c704c63d937079f506 to your computer and use it in GitHub Desktop.
Save groob/cc4b4cca4937e4c704c63d937079f506 to your computer and use it in GitHub Desktop.
import Foundation
func cost(_ mass: Int) -> Int {
return (mass/3) - 2
}
func moduleCost(_ mass: Int, _ sum: Int = 0) -> Int {
let remainder = cost(mass)
let sum = sum + remainder
if cost(remainder) <= 0 {
return sum
}
return moduleCost(remainder, sum)
}
func totalFuelCost(fileURL: URL) throws -> Int {
return try String(contentsOf: fileURL)
.split(separator: "\n")
.map{ line in Int(String(line))! }
.map{ mass in moduleCost(mass) }
.reduce(0,+)
}
try totalFuelCost(fileURL: #fileLiteral(resourceName: "Day 1.txt"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment