import{readFileSync}from'fs'// data as arrayconstdata=readFileSync('./data',{encoding:'utf8'}).trim().split(" ").map(Number)// recursive fn// return the index that the current child ends and the children metadataconstaddNode=(index)=>{letchildren=data[index]letmetadata=data[index+1]lettotalMetadata=0while(children>0){constchildData=addNode(index+2)index=childData.newIndextotalMetadata+=childData.totalMetadatachildren--}for(leti=0;i<metadata;i++){totalMetadata+=data[index+i+2]}return{newIndex:index+metadata,totalMetadata}}console.log(addNode(0).totalMetadata)
Part 2
import{readFileSync}from'fs'constdata=readFileSync('./data',{encoding:'utf8'}).trim().split(" ").map(Number)// recursive fn// return the child index, metadata qty, and the metadata for the childsconstaddNode=(index)=>{constrealIndex=indexletchildren=data[index]letmetadata=data[index+1]lettotalMetadata=0letchildrenMetadata=[]if(children>0){for(leti=0;i<children;i++){constchildData=addNode(index+2)index=childData.newIndexchildrenMetadata[i]=childData.totalMetadata}for(leti=0;i<metadata;i++){constchildMetadataToGet=data[index+i+2]-1totalMetadata+=(childrenMetadata[childMetadataToGet]||0)}}else{for(leti=0;i<metadata;i++){totalMetadata+=data[index+i+2]}}return{newIndex:index+metadata,totalMetadata,childrenMetadata}}console.log(addNode(0).totalMetadata)
This is my js solution using recursive functions
Part1
Part 2
github.com/ngleich/adventofcode2018/