aoc-2018-python

Advent of Code 2018 Solutions in Python
git clone https://git.sinitax.com/sinitax/aoc-2018-python
Log | Files | Refs | README | sfeed.txt

solve.py (1069B)


      1import sys
      2sys.path.append("../common")
      3import aoc
      4
      5data = [int(v) for v in aoc.data.split(" ")]
      6
      7def get_nodes(nsize, index):
      8    nodes = list()
      9    for i in range(nsize):
     10        cnsize = data[index + 0]
     11        mdsize = data[index + 1]
     12        cnodes, index = get_nodes(cnsize, index + 2)
     13        metadata = data[index:index + mdsize]
     14        nodes.append([cnodes, metadata])
     15        index = index + mdsize
     16    return nodes, index
     17
     18def node_sum(nodes):
     19    metadata = 0
     20    for n in nodes:
     21        metadata += sum(n[1]) + node_sum(n[0])
     22    return metadata
     23
     24def nodeValue(n):
     25    if len(n[0]) == 0:
     26        return sum(n[1])
     27    else:
     28        value = 0
     29        for i in range(len(n[1])):
     30            ni = n[1][i]-1
     31            if ni < len(n[0]):
     32                value += nodeValue(n[0][ni])
     33        return value
     34
     35def solve1(args):
     36    nodes, index = get_nodes(1, 0)
     37    return node_sum(nodes)
     38
     39def solve2(args):
     40    nodes, index = get_nodes(1, 0)
     41    return nodeValue(nodes[0])
     42
     43aoc.run(solve1, solve2, sols=[36307, 25154])