Advertisement
musifter

AoC 2021 day 4 (Smalltalk)

Dec 4th, 2021
2,069
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) + 1) ]
  6. ]
  7.  
  8. Object subclass: Card [
  9.     | score numbers lines |
  10.     Card class >> new: string [
  11.         ^(super new) init: string
  12.     ]
  13.  
  14.     init: string [
  15.         score   := 0.                         " sum of numbers left"
  16.         lines   := Array new: 10 withAll: 0.  " num squares marked in line "
  17.         numbers := Dictionary new.            " map number to its lines (row, col) "
  18.  
  19.         " Parse card "
  20.         string lines keysAndValuesDo: [ :y :row |
  21.             (row substrings apply: #asNumber) keysAndValuesDo: [ :x :n |
  22.                 score := score + n.
  23.                 numbers at: n put: { x. 5 + y }
  24.             ]
  25.         ].
  26.         ^self
  27.     ]
  28.  
  29.     call: num [
  30.         (numbers includesKey: num) ifTrue: [
  31.             score := score - num.
  32.             (numbers at: num) do: [ :linenum |
  33.                 ((lines incAt: linenum) = 5) ifTrue: [
  34.                     ^score * num
  35.                 ]
  36.             ]
  37.         ].
  38.         ^nil
  39.     ]
  40. ]
  41.  
  42. "
  43. | Mainline
  44. "
  45. sections := stdin contents tokenize: '\n\n'.
  46.  
  47. calls := (sections first tokenize: ',') apply: #asNumber.
  48. cards := Set from: (sections allButFirst collect: [:block | Card new: block]).
  49.  
  50. first := true.
  51. calls do: [ :num |
  52.     cards do: [ :card |
  53.         score := card call: num.
  54.         (score) ifNotNil: [
  55.             (first) ifTrue: [
  56.                 ('Part 1: %1' % {score}) displayNl.
  57.                 first := false
  58.             ].
  59.  
  60.             cards remove: card.
  61.  
  62.             (cards isEmpty) ifTrue: [
  63.                 ('Part 2: %1' % {score}) displayNl
  64.             ]
  65.         ]
  66.     ]
  67. ]
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement