| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- function Node(buf) {
- this.nodes = [];
- this.meta = [];
- var nbNodes = buf.data[buf.offset++],
- nbMeta = buf.data[buf.offset++];
- for (var i =0; i < nbNodes; ++i)
- this.nodes.push(new Node(buf));
- for (var i =0; i < nbMeta; ++i)
- this.meta.push(buf.data[buf.offset++]);
- }
- Node.prototype.sumMeta = function() {
- var result = 0;
- for (var i =0, len =this.nodes.length; i < len; ++i)
- result += this.nodes[i].sumMeta();
- for (var i =0, len =this.meta.length; i < len; ++i)
- result += this.meta[i];
- return result;
- }
- Node.prototype.value = function() {
- if (this.nodes.length > 0) {
- var result = 0;
- for (var i =0, len =this.meta.length; i < len; ++i)
- if (this.meta[i] <= this.nodes.length)
- result += this.nodes[this.meta[i] -1].value();
- return result;
- }
- return this.sumMeta();
- }
- function read(done) {
- require("fs").readFile('./input', 'utf8', (err, data) => {
- done(new Node({
- data: data.split(/\D+/).map(i => parseInt(i)),
- offset: 0
- }));
- });
- }
- function ex1() {
- read(root => {
- console.log("Sum of metas: " +root.sumMeta())
- console.log("value of root: " +root.value())
- });
- }
- function ex2() {
- read(function(data){
- });
- }
- ex1();
- //ex2();
|