DEV Community

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

Collapse
 
xgyrosx profile image
dimitri • Edited

I'm also participating this year. I want to solve everything in JS, as I'm new to web development (mostly frontend with React) on my job, too.

gitlab.com/xgyrosx/adventofcode

Part1

var fs = require("fs");
var text = fs.readFileSync("./data.txt").toString('utf-8');
var textByLine = text.split("\n");

var sum = 0;

for(i=0; i < textByLine.length; i++){
    textByLine[i] = parseInt(textByLine[i]);
    textByLine[i] = Math.floor(textByLine[i]/3)-2;
    sum += textByLine[i];
}
console.log(sum);

Part2

var fs = require("fs");
var text = fs.readFileSync("./data.txt").toString('utf-8');
var textByLine = text.split("\n");

var sum = 0;
var fuels = [];

function calculateFuel(module){
    if(module > 0) {
        module = Math.floor(module/3)-2;
        if (module > 0) {
            fuels.push(module)
        } else {
            return null;
        }
        calculateFuel(module);
    } else {
        return null;
    }
}

for(i=0; i < textByLine.length; i++){
    textByLine[i] = parseInt(textByLine[i]);
    textByLine[i] = calculateFuel(textByLine[i]);
}

for(j=0; j < fuels.length; j++){
    sum += fuels[j];
}

console.log(sum);

It took my quiet some time, especially for the file IO as there are so many approaches.