Advertisement
musifter

AoC 2023, day 2 (Smalltalk)

Dec 2nd, 2023 (edited)
1,259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 2.28 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. Collection extend [
  4.     product [ ^self inject: 1 into: [:a :b | a * b] ]
  5. ]
  6.  
  7. "
  8. | XXX: Not robust or complete, so play nice.  Doing this because even though Bag exists,
  9. | it doesn't have Set operations. Bag also doesn't have great functionality for
  10. | extending to do these... most notably is the lack of being able to remove multiple
  11. | of an item.  So, Dictionary it is.
  12. |
  13. | Note there's noting preventing negative amounts of items. Or zero being stored and
  14. | making isEmpty fail.  We do handle these with the difference operator, so isEmpty
  15. | is safe after that.
  16. "
  17. Dictionary subclass: MultiSet [
  18.     <shape: #pointer>
  19.  
  20.     " Union of self with aMultiSet "
  21.     + aMultiSet [
  22.         ^MultiSet from: ((aMultiSet keys + self keys) collect: [ :key |
  23.                             key -> ((aMultiSet at: key ifAbsent: [0])
  24.                                     max: (self at: key ifAbsent: [0])).
  25.                         ]).
  26.     ]
  27.  
  28.     " Difference of self with aMultiSet "
  29.     - aMultiSet [
  30.         ^MultiSet from: (self keys collect: [ :key |
  31.                            | diff |
  32.                             diff := (self at: key ifAbsent: [0]) - (aMultiSet at: key ifAbsent: [0]).
  33.                             (diff > 0) ifTrue: [ key -> diff ].
  34.                         ]).
  35.     ]
  36. ]
  37.  
  38. " Number of cubes we're testing  for: "
  39. want := MultiSet from: {#red -> 12. #green -> 13. #blue -> 14}.
  40.  
  41. part1 := 0.
  42. part2 := 0.
  43.  
  44. stdin linesDo: [ :line |
  45.     sections := line subStrings: ':'.
  46.  
  47.     game  := sections first subStrings last asNumber.           " Game num:"
  48.     draws := (sections second subStrings: ',;') collect: [ :draw |
  49.                 | pair |
  50.                  pair := draw subStrings.                       " num colour"
  51.                  pair second asSymbol -> pair first asNumber
  52.              ].
  53.  
  54.     " Get max seen for each colour of cube by unioning draws together. "
  55.     maxSeen := draws inject: (MultiSet new) into: [:a :draw | a + (MultiSet from: {draw})].
  56.  
  57.     " We want to see nothing more (including puce cubes) than what we want. "
  58.     (maxSeen - want) isEmpty ifTrue: [
  59.         part1 := part1 + game.
  60.     ].
  61.  
  62.     part2 := part2 + maxSeen values product.
  63. ].
  64.  
  65. ('Part 1: %1' % {part1}) displayNl.
  66. ('Part 2: %1' % {part2}) displayNl.
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement