Day 1: The Tyranny of the Rocket Equation

https://adventofcode.com/2019/day/1


In [1]:
inputLines = lines <$> readFile "input/day1.txt"

Part 1


In [2]:
fuelRequired1 :: Int -> Int
fuelRequired1 mass = (mass `div` 3) - 2

Verify given examples


In [3]:
fuelRequired1 12 == 2 && fuelRequired1 14 == 2 && fuelRequired1 1969 == 654 && fuelRequired1 100756 == 33583


True

Solution


In [4]:
sum <$> map (fuelRequired1 . read) <$> inputLines


3271994

Part 2


In [5]:
fuelRequired2 :: Int -> Int
fuelRequired2 mass
    | fuel <= 0 = 0
    | otherwise = fuel + fuelRequired2 fuel
    where fuel = fuelRequired1 mass

Verify given examples


In [6]:
fuelRequired2 14 == 2 && fuelRequired2 1969 == 966 && fuelRequired2 100756 == 50346


True

Solution


In [7]:
sum <$> map (fuelRequired2 .read) <$> inputLines


4905116

Alternative solution: sum the series generated by iterate fuelRequired1


In [8]:
sum . map (sum . takeWhile (>=0) . tail . iterate fuelRequired1 . read) <$> inputLines


4905116