main.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. function Node(buf) {
  2. this.nodes = [];
  3. this.meta = [];
  4. var nbNodes = buf.data[buf.offset++],
  5. nbMeta = buf.data[buf.offset++];
  6. for (var i =0; i < nbNodes; ++i)
  7. this.nodes.push(new Node(buf));
  8. for (var i =0; i < nbMeta; ++i)
  9. this.meta.push(buf.data[buf.offset++]);
  10. }
  11. Node.prototype.sumMeta = function() {
  12. var result = 0;
  13. for (var i =0, len =this.nodes.length; i < len; ++i)
  14. result += this.nodes[i].sumMeta();
  15. for (var i =0, len =this.meta.length; i < len; ++i)
  16. result += this.meta[i];
  17. return result;
  18. }
  19. Node.prototype.value = function() {
  20. if (this.nodes.length > 0) {
  21. var result = 0;
  22. for (var i =0, len =this.meta.length; i < len; ++i)
  23. if (this.meta[i] <= this.nodes.length)
  24. result += this.nodes[this.meta[i] -1].value();
  25. return result;
  26. }
  27. return this.sumMeta();
  28. }
  29. function read(done) {
  30. require("fs").readFile('./input', 'utf8', (err, data) => {
  31. done(new Node({
  32. data: data.split(/\D+/).map(i => parseInt(i)),
  33. offset: 0
  34. }));
  35. });
  36. }
  37. function ex1() {
  38. read(root => {
  39. console.log("Sum of metas: " +root.sumMeta())
  40. console.log("value of root: " +root.value())
  41. });
  42. }
  43. function ex2() {
  44. read(function(data){
  45. });
  46. }
  47. ex1();
  48. //ex2();