0x0049

Advent of Code | Day 7

Dec 7th, 2015
173
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Reads wires into an array then calls fn().
  2. function readFile(file, fn) {
  3.     require('readline').createInterface({
  4.         input: require('fs').createReadStream(file)
  5.     })
  6.     .on('line', function (line) {
  7.         var pieces = line.split(' -> ');
  8.         wires[pieces[1]] = pieces[0];
  9.     })
  10.     .on('close', fn);
  11. }
  12.  
  13. var wires = {}, calculated = {}, mask = 65535;
  14.  
  15. var ops = {
  16.     AND: function(a, b) { return a & b; },
  17.     OR: function (a, b) { return a | b; },
  18.     XOR: function (a, b) { return a ^ b; },
  19.     NOT: function (a) { return ~ a; },
  20.     LSHIFT: function (a, b) { return a << b; },
  21.     RSHIFT: function (a, b) { return a >> b; }
  22. };
  23.  
  24. // Recursively calculate the signal to this wire.
  25. function calculate(wire) {
  26.     if (!isNaN(wire))   return parseInt(wire);
  27.     if (calculated[wire]) return calculated[wire];
  28.  
  29.     var input = wires[wire].split(' '), length = input.length; // Note: inputs must only be strings.
  30.     if (length === 1) calculated[wire] = calculate(input[0]);
  31.     else if (length === 2) calculated[wire] = ops.AND(ops[input[0]](calculate(input[1])), mask);
  32.     else if (length === 3) calculated[wire] = ops.AND(ops[input[1]](calculate(input[0]), calculate(input[2])), mask);
  33.  
  34.     return calculated[wire];
  35. }
  36.  
  37. // Accept wire and file as arguments. Can also use "all" instead of a wire.
  38. var wire = process.argv[2] ? process.argv[2] : 'a';
  39. var file = process.argv[3] ? process.argv[3] : 'day7_input';
  40. readFile(file, function() {
  41.     if (wire === 'all') {
  42.         Object.keys(wires).map(calculate);
  43.         console.log(calculated);
  44.     }
  45.     else {
  46.         calculate(wire);
  47.         console.log(calculated[wire])
  48.     }
  49. });
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment