Advertisement
musifter

AoC 2023, day 4 (Smalltalk)

Dec 4th, 2023
1,683
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 0.92 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. Collection extend [
  4.     at: idx inc: val [ ^self at: idx put: val + (self at: idx) ]
  5.     sum              [ ^self inject: 0 into: [:a :b | a + b]   ]
  6. ]
  7.  
  8. " Convert input into a list of number of wins on each card: "
  9. cardWins := stdin lines contents collect: [ :line |
  10.                 parts := line subStrings: ':|'.
  11.                 wins  := parts second subStrings asSet.
  12.                 parts third subStrings count: [:n | wins includes: n].
  13.             ].
  14.  
  15. " Note: using floor to handle the 0 wins case, as 2^-1 = 1/2 "
  16. part1 := (cardWins collect: [:n | (2 raisedTo: n - 1) floor]) sum.
  17.  
  18. " Part 2: Start with one of each card, propagate wins forwards: "
  19. cards := Array new: cardWins size withAll: 1.
  20. cards keysAndValuesDo: [ :card :num |
  21.     (card + 1 to: card + (cardWins at: card)) do: [:i | cards at: i inc: num].
  22. ].
  23.  
  24. ('Part 1: %1' % {part1}) displayNl.
  25. ('Part 2: %1' % {cards sum}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement