Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- Symbol extend [ value: arg [ ^arg perform: self ] ]
- Collection extend [ sum [^self inject: 0 into: [:a :b | a + b]] ]
- Object subclass: DigitGrid [
- | grid dirs dimY dimX heads |
- DigitGrid class >> new: mapArray [ ^super new init: mapArray ]
- " Read in grid to flat array, add sentinels, make list of trailheads "
- init: mapArray [
- | sent |
- dimY := mapArray size + 2.
- dimX := (mapArray at: 1) size + 2.
- dirs := {dimX. 1. -1 * dimX. -1}.
- sent := Array new: dimX withAll: 99.
- grid := sent, (mapArray collect: [:row | {99}, row, {99}]) join, sent.
- heads := (1 to: grid size) select: [:idx | (grid at: idx) == 0].
- ^self
- ]
- " Recursive search: collect tails at height 9 from pos "
- walkTo: pos nextHeight: next [
- | tails |
- tails := Bag new.
- (next == 10) ifTrue: [^tails add: pos; yourself].
- (dirs collect: [:d | pos + d]) do: [:npos |
- ((grid at: npos) == next) ifTrue: [
- tails addAll: (self walkTo: npos nextHeight: next + 1).
- ]
- ].
- ^tails
- ]
- " Find all trails, return Dictionary of head to Bag of tails "
- getTrails [
- | res |
- res := Dictionary new.
- heads do: [:head |
- res at: head put: (self walkTo: head nextHeight: 1)
- ].
- ^res
- ]
- ]
- "
- | Mainline
- "
- grid := DigitGrid new: (stdin lines contents collect: [:row | row asArray collect: #digitValue]).
- trails := grid getTrails.
- " Part 1 is sum of unique tails from each head: "
- ('Part 1: %1' % {(trails collect: [:head | head asSet size]) sum}) displayNl.
- " Part 2 is sum of the size of all Bags (routes): "
- ('Part 2: %1' % {(trails collect: #size) sum}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement