Advertisement
musifter

AoC 2022, day 9 (smalltalk)

Dec 9th, 2022
2,788
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 1.53 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. Point extend [
  4.     " Distance and moveDelta calcuations extenstions for this problem "
  5.     distance:  pt [ ^(self x - pt x) abs max: (self y - pt y) abs ]
  6.     moveDelta: pt [ ^(pt x - self x) sign @ (pt y - self y) sign  ]
  7. ]
  8.  
  9. SequenceableCollection extend [
  10.     " Returns collection of results from calling binBlock for each link pair, "
  11.     " with 'item' added to the front.                                         "
  12.     inject: item intoChain: binBlock [
  13.         | res |
  14.         res := self copyEmptyForCollect.
  15.         self inject: item into: [:prev :curr| res add: (binBlock value: prev value: curr). curr].
  16.         ^res
  17.     ]
  18. ]
  19.  
  20. "
  21. | Mainline
  22. "
  23. dirs := Dictionary from: {'R' -> (0 @ 1). 'L' -> ( 0 @ -1).
  24.                           'D' -> (1 @ 0). 'U' -> (-1 @  0)}.
  25.  
  26. rope   := OrderedCollection from: ((1 to: 10) collect: [:x | (0 @ 0)]).
  27. trails := Array from: { Set with: (0 @ 0). Set with: (0 @ 0) }.
  28.  
  29. stdin linesDo: [ :line |
  30.     cmd := line substrings.
  31.  
  32.     cmd second asNumber timesRepeat: [
  33.         rope at: 1 put: (rope first + (dirs at: cmd first)).
  34.  
  35.         rope := rope inject: (rope first) intoChain: [ :prev :curr |
  36.                     curr + ((prev distance: curr) > 1 ifTrue:  [curr moveDelta: prev]
  37.                                                       ifFalse: [0 @ 0])
  38.                 ].
  39.  
  40.         trails first  add: rope second.
  41.         trails second add: rope last.
  42.     ]
  43. ].
  44.  
  45.  
  46. ('Part 1: %1' % {trails first  size}) displayNl.
  47. ('Part 2: %1' % {trails second size}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement