Advertisement
musifter

AoC day 13, Smalltalk

Dec 13th, 2020 (edited)
2,046
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/local/bin/gst -q
  2.  
  3. " Read input file "
  4. inStream := stdin lines contents readStream.
  5. now  := inStream next asNumber.
  6. table := (inStream next subStrings: ',')
  7.             collect: [ :a | (a ~= 'x') ifTrue:  [ a asNumber ]
  8.                                        ifFalse: [ a ] ].
  9.  
  10. " Part 1 "
  11. " Build arrival table of associations (bus id -> arrival time), take first. "
  12. buses  := table   select: [ :a | a ~= 'x' ].
  13. arrive := buses  collect: [ :b | (b -> (b - (now \\ b))) ].
  14. next   := (arrive sorted: [ :a :b | (a value < b value) ]) first.
  15.  
  16. stdout nextPutAll: 'Part 1: ', (next key * next value) asString; nl.
  17.  
  18. " Part 2 "
  19. " Get system of modular equations, as associations (mod -> targ) "
  20. equat := SortedCollection sortBlock: [ :a :b | a key > b key ].
  21. table doWithIndex: [ :b : i |
  22.     (b ~= 'x') ifTrue: [ equat add: (b -> ((b - i + 1) \\ b)) ].
  23. ].
  24.  
  25. " Find solution to system of equations with sieve: "
  26. part2 := equat fold: [ :a :b |
  27.              [ (a value \\ b key) ~= b value ] whileTrue: [
  28.                  a value: (a value + a key).
  29.              ].
  30.              a key: (a key * b key).
  31.          ].
  32.  
  33. stdout nextPutAll: 'Part 2: ', part2 value asString; nl.
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement