Advertisement
musifter

AoC 2021 day14 (smalltalk)

Dec 14th, 2021
2,121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/local/bin/gst -q
  2.  
  3. Character extend [
  4.     , chr  [ ^self asString, chr asString ]
  5. ]
  6.  
  7. SequenceableCollection extend [
  8.     " Returns collection of results from calling binBlock for each link pair "
  9.     chain: binBlock [
  10.         | res |
  11.         res := self copyEmptyForCollect.
  12.         self fold: [:curr :next | res add: (binBlock value: curr value: next). next].
  13.         ^res
  14.     ]
  15. ]
  16.  
  17. Object subclass: Polymer [
  18.     | start rules |
  19.  
  20.     Polymer class >> new: start withRules: lines [
  21.         ^super new init: start rules: lines
  22.     ]
  23.  
  24.     init: str rules: lines [
  25.         start := str asOrderedCollection.
  26.         rules := Dictionary from: (lines collect: [ :line |
  27.                     | parts |
  28.                      parts := line tokenize: ' -> '.
  29.                      parts first -> parts second first
  30.                  ]).
  31.         ^self.
  32.     ]
  33.  
  34.     elementsAfter: steps [
  35.         | pairs elements |
  36.         pairs := Bag from: (start chain: [:a :b | a,b]).
  37.  
  38.         " Track number of each adjacent pair across the steps "
  39.         steps timesRepeat: [
  40.             | new_pairs |
  41.             new_pairs := Bag new.
  42.  
  43.             pairs contents keysAndValuesDo: [ :pair :num |
  44.                | insert |
  45.                 insert := rules at: pair.
  46.  
  47.                 new_pairs add: (pair first,  insert) withOccurrences: num.
  48.                 new_pairs add: (insert, pair second) withOccurrences: num.
  49.             ].
  50.  
  51.             pairs := new_pairs.
  52.         ].
  53.  
  54.         " Convert pairs into counts of each element "
  55.         elements := Bag from: {start first. start last}.
  56.         pairs contents keysAndValuesDo: [ :pair :num |
  57.             pair do: [ :el | elements add: el withOccurrences: num ]
  58.         ].
  59.  
  60.         " each element counted twice (once from each side) so /2 "
  61.         ^elements sortedByCount collect: [:a | (a key / 2) -> a value].
  62.     ]
  63. ]
  64.  
  65. "
  66. | Mainline
  67. "
  68. input := stdin lines contents.
  69.  
  70. poly := Polymer new: input first withRules: (input allButFirst: 2).
  71.  
  72. { 1 -> 10. 2 -> 40 } do: [ :part |
  73.     elem := poly elementsAfter: part value.
  74.     ('Part %1: %2' % {part key. elem first key - elem last key}) displayNl.
  75. ].
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement