Created
December 8, 2018 08:12
-
-
Save mvmaasakkers/0cdaf9a991c945b771a7bdc2d6c0fe64 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"strconv" | |
"strings" | |
) | |
func readInput(filename string) []int { | |
t, err := ioutil.ReadFile(filename) | |
if err != nil { | |
log.Fatal(err) | |
} | |
in := strings.Split(string(t), " ") | |
for _, i := range in { | |
n, _ := strconv.ParseInt(i, 10, 32) | |
input = append(input, int(n)) | |
} | |
return input | |
} | |
var file = flag.String("file", "./input.txt", "file used for input") | |
var input = []int{} | |
func main() { | |
flag.Parse() | |
readInput(*file) | |
p1, p2 := parts() | |
fmt.Println(p1, p2) | |
} | |
type node struct { | |
header nodeHeader | |
children []node | |
metadata []int | |
value int | |
} | |
type nodeHeader struct { | |
childNodes int | |
metadataEntries int | |
} | |
var curPos = 2 | |
var part1sum = 0 | |
func parts() (int, int) { | |
n := getNodeValues(getNode(node{ | |
header: nodeHeader{ | |
childNodes: input[0], | |
metadataEntries: input[1], | |
}})) | |
return part1sum, n.value | |
} | |
func getNode(n node) node { | |
for x := 0; x < n.header.childNodes; x++ { | |
newNode := node{} | |
newNode.header.childNodes = input[curPos] | |
curPos++ | |
newNode.header.metadataEntries = input[curPos] | |
curPos++ | |
n.children = append(n.children, getNode(newNode)) | |
} | |
for x := 0; x < n.header.metadataEntries; x++ { | |
md := input[curPos] | |
n.metadata = append(n.metadata, md) | |
part1sum += md | |
if n.header.childNodes == 0 { | |
n.value += md | |
} | |
curPos++ | |
} | |
return n | |
} | |
func getNodeValues(n node) node { | |
for k, v := range n.children { | |
n.children[k] = getNodeValues(v) | |
} | |
for x := 0; x < len(n.metadata); x++ { | |
id := n.metadata[x] - 1 | |
if len(n.children) > id { | |
n.value += n.children[id].value | |
} | |
} | |
return n | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment