Browse Source

Tidy and optimise day 14 a little

master
Chris Smith 5 years ago
parent
commit
877a6cca07
1 changed files with 13 additions and 7 deletions
  1. 13
    7
      day14.nim

+ 13
- 7
day14.nim View File

@@ -3,9 +3,8 @@ import sequtils, strutils
3 3
 let
4 4
     input = readFile("data/14.txt").strip
5 5
     inputSeq = input.map do (c: char) -> int8: cast[int8](c.int - '0'.int)
6
-    inputHead = inputSeq[0..inputSeq.len-2]
7
-    lastDigit = inputSeq[inputSeq.len - 1]
8 6
     inputInt = input.parseInt
7
+    inputLen = input.len
9 8
 
10 9
 var
11 10
     scores: array[50_000_000, int8]  # Arbitrary large preallocation
@@ -14,6 +13,16 @@ var
14 13
     elf2 = 1
15 14
     part2 = -1
16 15
 
16
+proc check(inputSeq: seq[int8], val: int, part2: var int) {.inline.} =
17
+    var found {.global.} = 0
18
+    if val == inputSeq[found]:
19
+        found.inc
20
+        if found == inputLen:
21
+            part2 = size - inputLen
22
+            found = 0
23
+    else:
24
+        found = 0
25
+
17 26
 scores[0] = 3
18 27
 scores[1] = 7
19 28
 
@@ -23,16 +32,13 @@ while size < inputInt + 10 or part2 == -1:
23 32
     if score >= 10:
24 33
         scores[size] = 1
25 34
         size.inc
26
-
27
-        if 1 == lastDigit and size > input.len and scores[size-input.len..size-2] == inputHead:
28
-            part2 = size - input.len
35
+        inputSeq.check(1, part2)
29 36
 
30 37
     let newScore = cast[int8](score mod 10)
31 38
     scores[size] = newScore
32 39
     size.inc
33 40
 
34
-    if newScore == lastDigit and size > input.len and scores[size-input.len..size-2] == inputHead:
35
-        part2 = size - input.len
41
+    inputSeq.check(newScore, part2)
36 42
 
37 43
     elf1 = (elf1 + scores[elf1] + 1) mod size
38 44
     elf2 = (elf2 + scores[elf2] + 1) mod size