DEV Community

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

Collapse
 
jnschrag profile image
Jacque Schrag

Ooh this is a great use of do...while. I went with the less elegant nested if for mine šŸ˜…

Part 1 (JavaScript)

const fs = require("fs");
const path = require("path");
const text = fs.readFileSync(path.join(__dirname) + "/input.txt", "utf8");
let output = text
  .split("\n")
  .map(d => calcFuelPerModule(d))
  .reduce((acc, curr) => acc + curr, 0);
console.log(output);

function calcFuelPerModule(mass) {
  return Math.floor(+mass / 3) - 2;
}

Part 2 (JavaScript)

const fs = require("fs");
const path = require("path");
const text = fs.readFileSync(path.join(__dirname) + "/input.txt", "utf8");
let output = text
  .split("\n")
  .map(d => calcFuel(d))
  .reduce((acc, curr) => acc + curr, 0);
console.log(output);

function calcFuel(mass) {
  let fuel = calcFuelPerModule(mass);
  if (fuel > 0) {
    let fuelFuel = calcFuel(fuel);
    if (fuelFuel > 0) {
      fuel += calcFuel(fuel);
    }
  }
  return fuel;
}

function calcFuelPerModule(mass) {
  return Math.floor(+mass / 3) - 2;
}
Collapse
 
lindakatcodes profile image
Linda Thompson

Still works well! As long as it gets you the answer, it's good! :)

I saw someone use a ternary operator, and was super impressed. Might refactor mine later today to test that. :) Didn't even think of it!