Here is my Golang solution for today's problem. It was more easy for me to solve today, but made me learn to use pointers in Golang to consume the input string. I don't think this is necessarily the best way to use pointers, but I liked the simplicity in this case.
packagemainimport("bufio""fmt""os""strconv""strings")// A simple structure of a node.typenodestruct{children[]nodemetaData[]int}// readLines reads a whole file into memory// and returns a slice of its lines.funcreadLines(pathstring)([]string,error){file,err:=os.Open(path)iferr!=nil{returnnil,err}deferfile.Close()varlines[]stringscanner:=bufio.NewScanner(file)forscanner.Scan(){lines=append(lines,scanner.Text())}returnlines,scanner.Err()}// function to consume elements from the input string.funcconsume(parseNodes*[]string)int{i,_:=strconv.Atoi((*parseNodes)[0])*parseNodes=(*parseNodes)[1:]returni}// function to parse a node from the input string.funcreadNode(parseNodes*[]string)node{// Read headernumChildren:=consume(parseNodes)numMetaData:=consume(parseNodes)// Read children:varchildren[]nodeforc:=0;c<numChildren;c++{children=append(children,readNode(parseNodes))}// Read meta data:varmetaData[]intform:=0;m<numMetaData;m++{metaData=append(metaData,consume(parseNodes))}// Create and return node:returnnode{children:children,metaData:metaData}}// function to get the sum of meta data from a given node.funcgetMeta(nodenode)int{// Read meta data of this node:meta:=node.metaData// Run through each child and get meta data:for_,c:=rangenode.children{meta=append(meta,getMeta(c))}varsumint// Sum the meta data:for_,m:=rangemeta{sum+=m}returnsum}// function to get the value of a given node.funcgetValue(nodenode)int{numChildren:=len(node.children)varvalueintifnumChildren==0{// If the node has no children return just the sum of// the meta data for thid node:value=getMeta(node)}else{// If this node has children return the sum of the// values for each child:for_,m:=rangenode.metaData{m--// for correct indexingifm>=0&&m<numChildren{// Only get value if index is not out of boundvalue+=getValue(node.children[m])}}}returnvalue}funcmain(){data,err:=readLines("input")iferr!=nil{panic(err)}nodeString:=strings.Split(data[0]," ")root:=readNode(&nodeString)fmt.Println("Part 1:")fmt.Println(getMeta(root))fmt.Println("Part 2:")fmt.Println(getValue(root))}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Here is my Golang solution for today's problem. It was more easy for me to solve today, but made me learn to use pointers in Golang to consume the input string. I don't think this is necessarily the best way to use pointers, but I liked the simplicity in this case.