Advertisement
musifter

AoC 2023 day 7 (Smalltalk)

Dec 7th, 2023 (edited)
1,175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 1.85 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. Symbol extend [ value: arg  [^arg perform: self] ]
  4. String extend [ asHexNumber [^Number readFrom: (ReadStream on: self) radix: 16] ]
  5.  
  6. Collection extend [ at: idx inc: val [^self at: idx put: ((self at: idx ifAbsent:[0]) + val)] ]
  7.  
  8. "
  9. | Mainline
  10. "
  11. input := stdin lines contents.
  12.  
  13. maps := {
  14.     {$A -> $E. $K -> $D. $Q -> $C. $J -> $B. $T -> $A}.     " Part 1 "
  15.     {$A -> $E. $K -> $D. $Q -> $C. $J -> $1. $T -> $A}.     " Part 2 "
  16. }.
  17.  
  18. (1 to: 2) do: [:part |
  19.     hands := input collect: [:line |
  20.                  parts := line subStrings.
  21.                  (maps at: part) do: [:map |
  22.                      parts first replaceAll: map key with: map value
  23.                  ].
  24.  
  25.                  " Count cards. "
  26.                  " One initialized to 0 so jokers always have something to increase "
  27.                  counts := Dictionary from: {$E -> 0}.
  28.                  parts first do: [:chr | counts at: chr inc: 1].
  29.  
  30.                  " Extract wilds from dictionary, jokers removed "
  31.                  wilds := counts at: $1 ifAbsent: [0].
  32.                  counts removeKey: $1 ifAbsent: [].
  33.  
  34.                  " Sort groups and add wilds to largest "
  35.                  groups := counts values sorted reverse.
  36.                  groups at: 1 inc: wilds.
  37.  
  38.                  " Make string and fill to 6 characters with 0s "
  39.                  groups := (groups collect: #asString) join.
  40.                  groups := groups, ($0 * (6 - groups size)).
  41.  
  42.                  {groups asNumber. parts first asHexNumber. parts second asNumber}
  43.              ].
  44.  
  45.     hands sort: [ :a :b | (a first < b first)
  46.                             or: [(a first = b first) and: [a second < b second]] ].
  47.  
  48.     winnings := 0.
  49.     hands keysAndValuesDo: [:i :hand | winnings := winnings + (i * hand third)].
  50.  
  51.     ('Part %1: %2' % {part. winnings}) displayNl.
  52. ]
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement