Skip to content

Instantly share code, notes, and snippets.

@groob
Created December 2, 2019 03:30
Show Gist options
  • Save groob/cc4b4cca4937e4c704c63d937079f506 to your computer and use it in GitHub Desktop.
Save groob/cc4b4cca4937e4c704c63d937079f506 to your computer and use it in GitHub Desktop.

Revisions

  1. groob created this gist Dec 2, 2019.
    24 changes: 24 additions & 0 deletions Advent2019_Day1.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    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"))