DEV Community

Discussion on: Advent of Code 2019 Solution Megathread - Day 1: The Tyranny of the Rocket Equation

Collapse
 
rizzu26 profile image
Rizwan

Bit late to the party!

Here is my solution in swift. Incase anyone would like followup code can be found here in Github

func fuel(forMass mass: Int) -> Int {
    return Int((Double(mass) / 3).rounded(.down) - 2)
}

func partOne() {
    var total = 0
    input.components(separatedBy: .newlines).map{ input in
        total = total + fuel(forMass: Int(input) ?? 0)
    }
    print(total)
}

func fuel(forMass mass: Int, includesFuelMass: Bool) -> Int {
    if !includesFuelMass {
        return fuel(forMass: mass)
    }

    var currentFuel = mass
    var total = 0
    while true {
        let fuels = fuel(forMass: currentFuel)
        if fuels < 0 {
            break
        }
        currentFuel = fuels
        total = total + currentFuel
    }
    return total
}

func partTwo() {
    var total = 0
    input.components(separatedBy: .newlines).map{ input in
        total = total + fuel(forMass: Int(input) ?? 0, includesFuelMass: true)
    }
    print(total)
}

partOne()
partTwo()