Login
7 branches 0 tags
Ben (Win10) Added a bunch of vector functions 72bb8f6 3 years ago 421 Commits
nujel / tests / fast / day10.nuj
#!/usr/bin/env nujel

[defun char-to-score [cc]
       [case cc
             [[#\)]     3]
             [[#\]]    57]
             [[#\}]  1197]
             [[#\>] 25137]
             [otherwise 0]]]

[defun p2-score [cc]
       [case cc
             [[#\)] 1]
             [[#\]] 2]
             [[#\}] 3]
             [[#\>] 4]
             [otherwise 0]]]

[defun calc-part2-score [stack α]
       [if-not stack α
               [calc-part2-score [cdr stack]
                                 [+ [* 5 α]
                                    [p2-score [car stack]]]]]]

[defun find-first-syntax-error [line]
       [def stack #nil]
       [try [\ [ε] [if [== [car ε] :return]
                       [cons :part1 [char-to-score [cadr ε]]]
                       [throw ε]]]
            [for [i 0 [string/length line]]
                 [def cc [char-at line i]]
                 [case cc
                       [[#\(] [set! stack [cons #\) stack]]]
                       [[#\{] [set! stack [cons #\} stack]]]
                       [[#\[] [set! stack [cons #\] stack]]]
                       [[#\<] [set! stack [cons #\> stack]]]
                       [[#\) #\} #\] #\>] [if [== cc [car stack]]
                                              [set! stack [cdr stack]]
                                              [throw [list :return cc i]]]]]]
            [calc-part2-score stack 0]]]

[def lines [split [file/read "tests/fast/day10.input"] "\n"]]
[def res [map lines find-first-syntax-error]]
[def p1-res [reduce res [\ [α β] [if [== :part1 [car β]] [+ α [cdr β]] α]] 0]]
[def incomplete-lines [list/sort [filter res [\ [α] [!= :part1 [car α]]]]]]
[def p2-res [list/ref incomplete-lines [/ [length incomplete-lines] 2]]]
[when [!= p1-res 315693]
      [throw [list :wrong-result "Wrong result" p1-res]]]
[when [!= p2-res 1870887234]
      [throw [list :wrong-result "Wrong result" p2-res]]]