SHARE
TWEET

day6.js

a guest Dec 6th, 2019 206 in 130 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // WEAPON
  2. // OF
  3. // DURGASOFT
  4. // ICON
  5. // OF
  6. // JAVASCRIPT
  7.  
  8. const fs = require('fs');
  9.  
  10. const inputFile = process.argv.includes('TEST') ? './day6-test.txt' : './day6.txt';
  11. const debugMode = process.argv.includes('DEBUG');
  12.  
  13. const data = fs.readFileSync(inputFile).toString().split('\n').map(line => line.split(')'));
  14.  
  15. function Node(name, parent=null, nodes) {
  16.     return {
  17.         nodes,
  18.         name,
  19.         parent,
  20.         orbits() {
  21.             return this.parent === null ? 0 : this.nodes[this.parent].orbits() + 1;
  22.         },
  23.         chainToRoot() {
  24.             return this.parent === null ? [this.name] : [this.name, ...this.nodes[this.parent].chainToRoot()];
  25.         },
  26.     };
  27. }
  28.  
  29. let nodes = {
  30.     addNode(name, parent=null) {
  31.         this[name] = Node(name, parent, this);
  32.     },
  33. };
  34.  
  35. nodes.addNode('COM');
  36. data.forEach(([parent, name]) => nodes.addNode(name, parent));
  37. let orbits = [];
  38. const what = ['addNode', 'undefined', 'cloneChroot',];
  39. for (let key of Object.keys(nodes))
  40.     if (!what.includes(key)) orbits.push(nodes[key].orbits());
  41. // part1
  42. console.log(`part 1: ${orbits.reduce((a, b) => a + b)}`);
  43.  
  44. const intersection = (arrA, arrB) => arrA.filter(x => arrB.includes(x));
  45. const intersectionRoot = intersection(nodes['YOU'].chainToRoot(), nodes['SAN'].chainToRoot())[0];
  46. nodes[intersectionRoot].parent = null;
  47. const p2 = nodes[nodes['YOU'].parent].orbits() + nodes[nodes['SAN'].parent].orbits();
  48. console.log(`part 2: ${p2}`);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top