Advertisement
musifter

AoC 2021 day11 (smalltalk)

Dec 11th, 2021
2,328
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/local/bin/gst -q
  2.  
  3. Collection extend [
  4.     apply: method  [ ^self collect: [:x | x perform: method] ]
  5.     incAt: idx     [ ^self at: idx put: ((self at: idx ifAbsent: [0]) + 1) ]
  6. ]
  7.  
  8. "
  9. |  Class to handle the 2D Grid
  10. "
  11. Object subclass: DigitGrid [
  12.     | grid xsize |
  13.  
  14.     dirs := { (-1@-1). (-1@ 0). (-1@ 1).
  15.               ( 0@-1).          ( 0@ 1).
  16.               ( 1@-1). ( 1@ 0). ( 1@ 1) }.
  17.  
  18.     DigitGrid class >> new: arrayStrings [
  19.         ^(super new) init: arrayStrings.
  20.     ]
  21.  
  22.     init: mapArray [
  23.         xsize := (mapArray at: 1) size.
  24.  
  25.         grid := Array from: (mapArray collect: [:line |
  26.                     line asArray apply: #digitValue
  27.                 ]).
  28.         ^self
  29.     ]
  30.  
  31.     " Access to grid by Points "
  32.     at: pt [
  33.         ^(grid at: pt y) at: pt x
  34.     ]
  35.  
  36.     at: pt put: chr [
  37.         ^(grid at: pt y) at: pt x put: chr
  38.     ]
  39.  
  40.     incAt: pt [
  41.         ^self at: pt put: ((self at: pt) + 1)
  42.     ]
  43.  
  44.     " Get coordinates of neighbours "
  45.     neighbours: pt [
  46.         ^(dirs collect: [:d | pt + d ]) select: [:n |
  47.             (n x between: 1 and: xsize) & (n y between: 1 and: grid size)
  48.         ]
  49.     ]
  50.  
  51.     " Execute a block on every Point of our input "
  52.     pointDo: aBlock [
  53.         (1 to: grid size) do: [ :y |
  54.             (1 to: xsize) do: [ :x |
  55.                 aBlock value: (x@y)
  56.             ]
  57.         ]
  58.     ]
  59. ]
  60.  
  61. "
  62. | Mainline
  63. "
  64. grid := DigitGrid new: stdin lines contents.
  65.  
  66. time    := 0.
  67. flashes := 0.
  68.  
  69. [
  70.     flashed := Dictionary new.
  71.     queue   := OrderedCollection new.
  72.  
  73.     grid pointDo: [:pt | ((grid incAt: pt) = 10) ifTrue: [queue add: pt]].
  74.  
  75.     [ queue notEmpty ] whileTrue: [
  76.         | pos |
  77.         pos := queue removeFirst.
  78.         ((flashed incAt: pos) = 1) ifTrue: [
  79.             (grid neighbours: pos) do: [ :pt |
  80.                 ((grid incAt: pt) = 10) ifTrue: [queue add: pt]
  81.             ]
  82.         ]
  83.     ].
  84.  
  85.     flashes := flashes + flashed keys size.
  86.     flashed keys do: [:pt | grid at: pt put: 0].
  87.  
  88.     ((time := time + 1) = 100) ifTrue: [
  89.         ('Part 1: %1' % {flashes}) displayNl.
  90.     ].
  91.  
  92.     (flashed keys size < 100)
  93. ] whileTrue.
  94.  
  95. ('Part 2: %1' % {time}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement