Advertisement
musifter

AoC day 12 (pt 1), Smalltalk

Dec 12th, 2020 (edited)
3,020
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/local/bin/gst -q
  2.  
  3. Point extend [
  4.     gridDist: pt [
  5.         ^((self x - pt x) abs + (self y - pt y) abs)
  6.     ]
  7. ]
  8.  
  9. Object subclass: Boat [
  10.     | pos face widder disp |
  11.  
  12.     Boat class >> new [
  13.         ^(super new) init.
  14.     ]
  15.  
  16.     init [
  17.         pos  := (0 @ 0).
  18.         face := 0.                    " facing, add 1 before using on array "
  19.         widder := #( #E #N #W #S ).   " directions in widdershin order      "
  20.  
  21.         disp := LookupTable new.
  22.         disp at: #N put: [ :m | pos y: (pos y + m) ];
  23.              at: #S put: [ :m | pos y: (pos y - m) ];
  24.              at: #E put: [ :m | pos x: (pos x + m) ];
  25.              at: #W put: [ :m | pos x: (pos x - m) ];
  26.              at: #L put: [ :m | face := (face + (m / 90)) \\ 4 ];
  27.              at: #R put: [ :m | face := (face - (m / 90)) \\ 4 ];
  28.              at: #F put: [ :m | (disp at: (widder at: (face+1))) value: m ].
  29.     ]
  30.  
  31.     do: cmd with: mag [
  32.         ^(disp at: cmd) value: mag.
  33.     ]
  34.  
  35.     pos  [ ^pos ]
  36. ]
  37.  
  38. parse_re := '(\w)(\d+)' asRegex.    " precompile regex for efficiency "
  39.  
  40. boat := Boat new.
  41. stdin linesDo: [ :line |
  42.     (line =~ parse_re) ifMatched: [ :results |
  43.         cmd := (results at: 1) asSymbol.
  44.         mag := (results at: 2) asNumber.
  45.  
  46.         boat do: cmd with: mag.
  47.     ]
  48. ].
  49.  
  50. stdout nextPutAll: ('Pos: ', boat pos printString); nl.
  51. stdout nextPutAll: ('Part 1: ', ((0@0) gridDist: boat pos) printString); nl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement