Advertisement
musifter

AoC 2024, day 4 (smalltalk)

Dec 4th, 2024 (edited)
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 2.00 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. Object subclass: TextGrid [
  4.     | grid dimX dimY |
  5.     " Directions: order is important for diags to work "
  6.     dirs  := {(-1 @ -1). ( 0 @ -1). ( 1 @ -1).
  7.               (-1 @  0).            ( 1 @  0).
  8.               (-1 @  1). ( 0 @  1). ( 1 @  1)}.
  9.  
  10.     TextGrid class >> dirs      [^dirs]
  11.     TextGrid class >> diags     [^dirs atAll: #(1 3 6 8)]
  12.  
  13.     TextGrid class >> new: mapArray [
  14.         ^super new init: mapArray
  15.     ]
  16.  
  17.     init: mapArray [
  18.         | sentinel |
  19.         dimY := mapArray size + 2.
  20.         dimX := mapArray first size + 2.
  21.  
  22.         " Add sentinels to all sides "
  23.         sentinel := (1 to: dimX) inject: '' into: [:a :b | a, '.'].
  24.         grid := sentinel, (mapArray collect: [:row | '.', row, '.']) join, sentinel.
  25.         ^self
  26.     ]
  27.  
  28.     " Access to grid via Points "
  29.     at: pt           [^grid at: (pt y * dimX) + pt x + 1]
  30.     at: pt put: chr  [^grid at: (pt y * dimX) + pt x + 1 put: chr]
  31.  
  32.     " Return array of Points where aBlock on that character returns true "
  33.     selectPoints: aBlock [
  34.         | res |
  35.         res := OrderedCollection new.
  36.         (1 to: dimY - 1) do: [:y |
  37.             (1 to: dimX - 1) do: [:x |
  38.                 (aBlock value: (self at: x @ y)) ifTrue: [res add: x @ y].
  39.             ]
  40.         ].
  41.         ^res
  42.     ]
  43. ]
  44.  
  45. "
  46. | Mainline
  47. "
  48. grid := TextGrid new: stdin lines contents.
  49.  
  50. " Part 1 "
  51. part1 := 0.
  52. (grid selectPoints: [:chr | chr == $X]) do: [:pt |
  53.     part1 := part1 + (TextGrid dirs count: [:d |
  54.                 (1 to: 3) conform: [:i | (grid at: (d * i + pt)) == ('MAS' at: i)]
  55.              ]).
  56. ].
  57.  
  58. ('Part 1: %1' % {part1}) displayNl.
  59.  
  60. " Part 2 "
  61. part2 := 0.
  62. (grid selectPoints: [:chr | chr == $A]) do: [:pt |
  63.     corners := TextGrid diags collect: [:d | grid at: pt + d].
  64.  
  65.     ((corners conform: [:c | (c == $M) | (c == $S)])
  66.         & (corners first  ~= corners fourth)
  67.         & (corners second ~= corners third)) ifTrue: [ part2 := part2 + 1 ].
  68. ].
  69.  
  70. ('Part 2: %1' % {part2}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement