DEV Community

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

Collapse
 
brandonschreck profile image
Brandon Schreck • Edited

Very nice, I need to step my JS game up!

const data = [148216, 142030, 129401, 74642, 108051, 54128, 145495, 67818, 120225, 67113, 
107672, 101032, 147714, 55788, 87732, 73681, 114646, 76586, 116436, 139788, 125150, 136675, 
90527, 74674, 105505, 146059, 52735, 101389, 108121, 62897, 132337, 51963, 129188, 122308, 
84677, 66433, 118374, 66822, 94714, 101162, 54030, 136580, 55677, 114051, 133898, 95026, 
112964, 68662, 85139, 53559, 84703, 92053, 132197, 60130, 63184, 86182, 113038, 52659, 
140463, 123234, 97887, 70216, 131832, 108162, 116759, 111828, 132815, 113476, 127734, 
134545, 99643, 141911, 74705, 65720, 95640, 51581, 66787, 147590, 72937, 148774, 
119881, 139875, 131976, 68238, 100342, 134691, 112320, 86107, 100045, 120458, 
54459, 52047, 108226, 102138, 141233, 54452, 67859, 105132, 81903, 104282];

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

function getTotalFuel(mass) {
  let fuel = calculateFuel(mass);
  return fuel > 0 ? fuel += getTotalFuel(fuel) : 0;
}

function outputTestResults(index, testCase, result) {
  console.log(`Test ${ index + 1 }\n` +
    `Input: ${ testCase.input }\n` +
    `Expected Result: ${ testCase.output }\n` +
    `Result: ${ result }\n` +
    `Passes Test: ${ testCase.output === result }\n\n`);
}

// Part One
console.log(`Begin Part One`);
let partOneResult = 0;
const partOneTestCases = [{
    input: 12,
    output: 2
  },
  {
    input: 14,
    output: 2
  },
  {
    input: 1969,
    output: 654
  },
  {
    input: 100756,
    output: 33583
  },
];

// part one test cases
partOneTestCases.forEach(function(testCase, index) {
  outputTestResults(index, testCase, calculateFuel(testCase.input));
});

// part one do work
data.forEach(function(mass) {
  partOneResult += calculateFuel(mass);
});
console.log(`Part One Answer: ${partOneResult}`);

// Part Two
console.log(`Begin Part Two`);
let partTwoResult = 0;
const partTwoTestCases = [{
    input: 14,
    output: 2
  },
  {
    input: 1969,
    output: 966
  },
  {
    input: 100756,
    output: 50346
  }
];

// part two test cases
partTwoTestCases.forEach(function(testCase, index) {
  outputTestResults(index, testCase, getTotalFuel(testCase.input));
});

// do work
data.forEach(function(mass) {
  partTwoResult += getTotalFuel(mass);
});
console.log(`Part Two Answer: ${partTwoResult}`);