loading...

re: Advent of Code 2019 Solution Megathread - Day 1: The Tyranny of the Rocket Equation VIEW POST

TOP OF THREAD FULL DISCUSSION
re: I would love to be part of some DEV leaderboards! I'm not showing myself as part of any right now, and am more than willing to use my own private o...
 

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;
}
 

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!

Code of Conduct Report abuse