Advertisement
musifter

AoC day 12 (pt 2), Smalltalk

Dec 12th, 2020 (edited)
2,031
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.     rot90: n [
  9.         ^n timesRepeat: [ self x: (self y negated) y: (self x) ]
  10.     ]
  11. ]
  12.  
  13. Object subclass: Boat [
  14.     | pos way disp |
  15.  
  16.     Boat class >> new [
  17.         ^(super new) init.
  18.     ]
  19.  
  20.     init [
  21.         pos := ( 0 @ 0).
  22.         way := (10 @ 1).
  23.  
  24.         disp := LookupTable new.
  25.         disp at: #N put: [ :m | way y: (way y + m) ];
  26.              at: #S put: [ :m | way y: (way y - m) ];
  27.              at: #E put: [ :m | way x: (way x + m) ];
  28.              at: #W put: [ :m | way x: (way x - m) ];
  29.              at: #L put: [ :m | way rot90: (m / 90) ];
  30.              at: #R put: [ :m | way rot90: (m / 90) negated + 4 ];
  31.              at: #F put: [ :m | pos := pos + (way * m) ].
  32.     ]
  33.  
  34.     do: cmd with: mag [
  35.         ^(disp at: cmd) value: mag.
  36.     ]
  37.  
  38.     pos  [ ^pos ]
  39. ]
  40.  
  41. parse_re := '(\w)(\d+)' asRegex.        " precompile regex for efficiency "
  42.  
  43. boat := Boat new.
  44. stdin linesDo: [ :line |
  45.     (line =~ parse_re) ifMatched: [ :results |
  46.         cmd := (results at: 1) asSymbol.
  47.         mag := (results at: 2) asNumber.
  48.  
  49.         boat do: cmd with: mag.
  50.     ]
  51. ].
  52.  
  53. stdout nextPutAll: ('Pos: ', boat pos printString); nl.
  54. stdout nextPutAll: ('Part 2: ', ((0@0) gridDist: boat pos) printString); nl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement