Advertisement
musifter

AoC 2024, day 10 (Smalltalk)

Dec 10th, 2024 (edited)
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 1.81 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. Symbol extend     [ value: arg [ ^arg perform: self ] ]
  4. Collection extend [ sum [^self inject: 0 into: [:a :b | a + b]] ]
  5.  
  6. Object subclass: DigitGrid [
  7.     | grid dirs dimY dimX heads |
  8.  
  9.     DigitGrid class >> new: mapArray [ ^super new init: mapArray ]
  10.  
  11.     " Read in grid to flat array, add sentinels, make list of trailheads "
  12.     init: mapArray [
  13.         | sent |
  14.         dimY  := mapArray size + 2.
  15.         dimX  := (mapArray at: 1) size + 2.
  16.         dirs  := {dimX. 1. -1 * dimX. -1}.
  17.  
  18.         sent  := Array new: dimX withAll: 99.
  19.         grid  := sent, (mapArray collect: [:row | {99}, row, {99}]) join, sent.
  20.  
  21.         heads := (1 to: grid size) select: [:idx | (grid at: idx) == 0].
  22.         ^self
  23.     ]
  24.  
  25.     " Recursive search: collect tails at height 9 from pos "
  26.     walkTo: pos nextHeight: next [
  27.         | tails |
  28.         tails := Bag new.
  29.         (next == 10) ifTrue: [^tails add: pos; yourself].
  30.  
  31.         (dirs collect: [:d | pos + d]) do: [:npos |
  32.             ((grid at: npos) == next) ifTrue: [
  33.                 tails addAll: (self walkTo: npos nextHeight: next + 1).
  34.             ]
  35.         ].
  36.         ^tails
  37.     ]
  38.  
  39.     " Find all trails, return Dictionary of head to Bag of tails "
  40.     getTrails [
  41.         | res |
  42.         res := Dictionary new.
  43.  
  44.         heads do: [:head |
  45.             res at: head put: (self walkTo: head nextHeight: 1)
  46.         ].
  47.         ^res
  48.     ]
  49. ]
  50.  
  51. "
  52. | Mainline
  53. "
  54. grid := DigitGrid new: (stdin lines contents collect: [:row | row asArray collect: #digitValue]).
  55.  
  56. trails := grid getTrails.
  57.  
  58. " Part 1 is sum of unique tails from each head: "
  59. ('Part 1: %1' % {(trails collect: [:head | head asSet size]) sum}) displayNl.
  60.  
  61. " Part 2 is sum of the size of all Bags (routes): "
  62. ('Part 2: %1' % {(trails collect: #size) sum}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement