Advertisement
musifter

AoC 2021 day 10 (smalltalk)

Dec 10th, 2021
2,003
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/local/bin/gst -q
  2.  
  3. String extend [
  4.     asRadix: rad [ ^Number readFrom: (ReadStream on: self) radix: rad ]
  5. ]
  6.  
  7. Character extend [
  8.     " Extension to Character to handle paired delimiters "
  9.     pairs := Dictionary from: { $( -> $). $[ -> $]. ${ -> $}. $< -> $> }.
  10.  
  11.     isOpen       [ ^pairs includesKey: self ]
  12.     closedBy     [ ^pairs at: self          ]
  13. ]
  14.  
  15. " Error class to throw on syntax errors... holds and scores token "
  16. Error subclass: SyntaxError [
  17.     | token |
  18.     table := Dictionary from: { $) -> 3. $] -> 57. $} -> 1197. $> -> 25137 }.
  19.  
  20.     SyntaxError class >> on: chr [
  21.         ^super new init: chr
  22.     ]
  23.  
  24.     init: chr [
  25.         token := chr.
  26.         ^self
  27.     ]
  28.  
  29.     score [
  30.         ^table at: token
  31.     ]
  32. ]
  33.  
  34. "
  35. | Mainline
  36. "
  37. part1 := 0.
  38. part2 := SortedCollection new.
  39.  
  40. stdin linesDo: [ :line |
  41.     stack   := OrderedCollection new.
  42.  
  43.     [
  44.         line do: [ :chr |
  45.             (chr isOpen) ifTrue: [
  46.                 stack addFirst: chr closedBy
  47.             ] ifFalse: [
  48.                 (chr ~= stack removeFirst) ifTrue: [(SyntaxError on: chr) signal]
  49.             ]
  50.         ]
  51.     ] on: SyntaxError do: [ :sig |
  52.         part1 := part1 + sig score.
  53.         stack empty     " corrupt, nothing to autocomplete "
  54.     ].
  55.  
  56.     " autocomplete if needed: "
  57.     (stack notEmpty) ifTrue: [
  58.         part2 add: ((stack gather: [:c | (')]}>' indexOf: c) asString]) asRadix: 5).
  59.     ]
  60. ].
  61.  
  62. ('Part 1: %1' % {part1}) displayNl.
  63. ('Part 2: %1' % {part2 at: (part2 size // 2 + 1)}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement