DEV Community

Steve Latham
Steve Latham

Posted on

Advent of Code (AoC) - Day 1

I thought I'd document my journey through AoC 2019. As I've been concentrating on learning React recently, I feel like some other basic concepts might be starting to fade from my memory banks!

Part one was very straight forward.

Read in the input numbers from the text file and stuff them into the calculation given to you: -

const readline = require('readline');
const fs = require('fs');

// set up the file for reading line-by-line
const readInterface = readline.createInterface({
    input: fs.createReadStream('./AoC1-input.txt')
});

// calculate fuel required given a mass
const getFuelRequirement = (mass) => {
    return fuel = Math.floor((mass / 3) - 2)
}

// calculate the total fuel requirement
// for all the masses listed in the file
const getTotalFuelRequirement = () => {
    let totalFuel = 0; 
    // on each new line, add the calculated requirement to
    // the totalFuel
    readInterface.on('line', (line) => {
        totalFuel += getFuelRequirement(line)
    });

    // at the end console log the total
    readInterface.on('close', () => {
        console.log(totalFuel)
    })
}

getTotalFuelRequirement()

Then, the spanner in the works for me came on part two. I think it was hinting at solving the problem with a recursive function. I was scrambling trying to get my brain into that mode of using recursion. I almost gave up, reverting to a solution without the recursive bit, but the reason I am doing this is to try to help me remember some concepts I'd let slip. So I persevered and came up with a solution: -

const readline = require('readline');
const fs = require('fs');

// set up the file for reading line-by-line
const readInterface = readline.createInterface({
    input: fs.createReadStream('./AoC1-input.txt'),
});

// calculate fuel required given a mass
const getFuelRequirement = (mass) => {

    let fuel = Math.floor((mass / 3) - 2)

    // base case -- fuel required is negative or zero
    if(fuel <= 0){
        return 0;
    }
    // recursive bit - fuel for the initial mass, plus the
    // fuel required for the fuel until it is zero
    return fuel + getFuelRequirement(fuel);

}

const getTotalFuelRequirement = () => {
    let totalFuel = 0; 
    readInterface.on('line', (line) => {
        totalFuel += getFuelRequirement(line)
    });
    readInterface.on('close', () => {
        console.log(totalFuel)
    })
}

getTotalFuelRequirement()

Top comments (0)