musifter

AoC 2024, day 8 (smalltalk)

Dec 8th, 2024 (edited)
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 2.26 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. OrderedCollection extend [
  4.     pairs [
  5.         | res |
  6.         res := OrderedCollection new.
  7.         self allButFirst keysAndValuesDo: [:i :elem1 |
  8.             res addAll: ((self first: i) collect: [:elem2 | {elem2. elem1}]).
  9.         ].
  10.         ^res
  11.     ]
  12. ]
  13.  
  14. Object subclass: AntennaMap [
  15.     | antenna bounds |
  16.  
  17.     AntennaMap class >> new: mapArray [
  18.         ^super new init: mapArray
  19.     ]
  20.  
  21.     init: mapArray [
  22.         bounds := Rectangle origin: (1@1) extent: (mapArray first size @ mapArray size).
  23.  
  24.         " Read array and build lists of antennae for each frequency: "
  25.         antenna := Dictionary new.
  26.         mapArray keysAndValuesDo: [:y :line |
  27.             line keysAndValuesDo: [:x :chr |
  28.                 (chr ~= $.) ifTrue: [
  29.                     (antenna at: chr ifAbsentPut: [OrderedCollection new]) add: x@y
  30.                 ]
  31.             ]
  32.         ].
  33.         ^self
  34.     ]
  35.  
  36.     validPoint: pt  [ ^bounds containsPoint: pt ]
  37.  
  38.     " Get harmonic multiple antinode of two antannae: "
  39.     aOne: ant1 aTwo: ant2 multiple: mult [
  40.         | delta |
  41.         delta := ant2 - ant1.
  42.         ^{ant1 - (delta * mult). ant2 + (delta * mult)} select: [:pt | self validPoint: pt]
  43.     ]
  44.  
  45.     " Get all antinodes with a set harmonic multiple: "
  46.     getAntinodes: mult [
  47.         | anti |
  48.         anti := Set new.
  49.         antenna do: [:ant |
  50.             ant pairs do: [ :pair |
  51.                 anti addAll: (self aOne: pair first aTwo: pair second multiple: mult)
  52.             ]
  53.         ].
  54.         ^anti
  55.     ]
  56.  
  57.     " Get all antinodes with all harmonic multiples: "
  58.     getAntinodes [
  59.         | anti |
  60.         anti := Set new.
  61.         antenna do: [:ant |
  62.             ant pairs do: [ :pair |
  63.                | mult harm |
  64.                 mult := 0.
  65.                 [
  66.                     harm := self aOne: pair first aTwo: pair second multiple: mult.
  67.                     mult := mult + 1.
  68.                     (anti addAll: harm) isEmpty. " Keep going until harm isEmpty "
  69.                 ] whileFalse.
  70.             ]
  71.         ].
  72.         ^anti
  73.     ]
  74. ]
  75.  
  76. "
  77. | Mainline
  78. "
  79. map := AntennaMap new: stdin lines contents.
  80.  
  81. ('Part 1: %1' % {(map getAntinodes: 1) size}) displayNl.
  82. ('Part 2: %1' % {map getAntinodes size}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment