DEV Community

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

Collapse
 
jbristow profile image
Jon Bristow

This part 2 solution is much more elegant, and leverages monads.

tailrec fun totalFuelNeeded(mass: Int, fuel: Option<Int> = Option.empty(), totalFuel: Int = 0): Int =
    when (val nextFuel = fuel.fold({ fuelNeeded(mass) }, ::fuelNeeded)) {
        0 -> totalFuel
        else -> totalFuelNeeded(mass, nextFuel.just(), totalFuel + nextFuel)
    }