Advertisement
musifter

AoC 2022, day 11 (smalltalk, part 1)

Dec 11th, 2022
2,123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 2.09 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. Collection extend [
  4.     apply: method  [ ^self collect: [:x | x perform: method] ]
  5.     prod           [ ^self inject: 1 into: [:a :b | a * b] ]
  6.     lcm            [ ^self fold: [:a :b | a lcm: b] ]
  7. ]
  8.  
  9. Object subclass: Monkey [
  10.     | num items op arg test pass checks |
  11.     Monkey class >> new: desc [
  12.         ^super new init: desc
  13.     ]
  14.  
  15.     init: desc [
  16.         " Monkey 0: (smalltalk arrays start at 1, so +1)"
  17.         num := desc first second asNumber + 1.
  18.  
  19.         " Starting items: 79, 98 "
  20.         items := (desc second allButFirst: 2) apply: #asNumber.
  21.  
  22.         " Operation: new = old + 19  (ASSUME 0 isn't used here)"
  23.         " Operation: new = old * old (... so 0 represents this)"
  24.         op  := (desc third at: 5) asSymbol.
  25.         arg := desc third last asNumber.
  26.  
  27.         " Test: divisible by 23 "
  28.         test := desc fourth last asNumber.
  29.  
  30.         " If true: throw to monkey 2  (+1 for array indexing)"
  31.         " If false: throw to monkey 3 (+1 for array indexing)"
  32.         pass := Dictionary from: {
  33.                     true  -> ((desc at: 5) last asNumber + 1).
  34.                     false -> ((desc at: 6) last asNumber + 1).
  35.                 }.
  36.  
  37.         checks := 0.
  38.         ^self
  39.     ]
  40.  
  41.     inspect: item [
  42.         checks := checks + 1.
  43.         ^item perform: op with: (arg = 0 ifTrue: [item] ifFalse: [arg]).
  44.     ]
  45.  
  46.     testPass: worry [
  47.         ^pass at: (worry \\ test = 0).
  48.     ]
  49.  
  50.     testValue  [ ^test   ]
  51.     items      [ ^items  ]
  52.     numInspect [ ^checks ]
  53. ]
  54.  
  55.  
  56. "
  57. | Mainline
  58. "
  59. monkeys := ((stdin contents tokenize: '\n\n') collect: [ :blk |
  60.                 blk lines apply: #substrings " break into lines and words "
  61.            ]) collect: [:txt | Monkey new: txt].
  62.  
  63. (1 to: 20) do: [ :round |
  64.     monkeys do: [ :monk |
  65.         [monk items notEmpty] whileTrue: [
  66.             | item |
  67.             item := (monk inspect: monk items removeFirst) // 3.
  68.             (monkeys at: (monk testPass: item)) items addLast: item.
  69.         ]
  70.     ]
  71. ].
  72.  
  73. ('Part 1: %1' % {((monkeys apply: #numInspect) sorted last: 2) prod}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement