Browse Source

Tidy up day 8

Reverse the input so we can just pop entries off the end as we use
them, instead of tracking offsets horribly.
master
Chris Smith 5 years ago
parent
commit
faa0f08901
1 changed files with 10 additions and 12 deletions
  1. 10
    12
      day08.nim

+ 10
- 12
day08.nim View File

@@ -1,32 +1,30 @@
1
-import math, sequtils, strutils
1
+import algorithm, math, sequtils, strutils
2 2
 
3
-func readNode(input: seq[string], start: int): tuple[value: int, metasum: int, offset: int] =
3
+func readNode(input: var seq[string]): tuple[value: int, metasum: int] =
4 4
     let
5
-        child_count = input[start + 0].parseInt
6
-        meta_count = input[start + 1].parseInt
5
+        child_count = input.pop.parseInt
6
+        meta_count = input.pop.parseInt
7 7
     var
8 8
         value = 0
9 9
         metasum = 0
10
-        offset = start + 2
11 10
         child_values: seq[int]
12 11
     
13 12
     for i in 0 .. child_count - 1:
14
-        var res = readNode(input, offset)
13
+        var res = readNode(input)
15 14
         child_values.add(res.value)
16
-        offset = res.offset
17 15
         metasum += res.metasum
18 16
 
19
-    for m in input[offset .. offset + meta_count - 1]:
20
-        var v = m.parseInt
17
+    for m in 0..meta_count-1:
18
+        var v = input.pop.parseInt
21 19
         if v > 0 and v - 1 < child_count:
22 20
             value += child_values[v - 1]
23 21
         metasum += v
24
-    offset += meta_count
25 22
     
26 23
     if child_count == 0:
27 24
         value = metasum
28
-    (value, metasum, offset)
25
+    (value, metasum)
29 26
 
30
-let root = readNode(readFile("data/08.txt").strip.split(" "), 0)
27
+var input = readFile("data/08.txt").strip.split(" ").reversed
28
+let root = input.readNode
31 29
 echo root.metasum
32 30
 echo root.value