Created
December 2, 2019 03:30
-
-
Save groob/cc4b4cca4937e4c704c63d937079f506 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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