Advertisement
musifter

AoC day 10, Smalltalk

Dec 10th, 2020
1,888
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/local/bin/gst -q
  2.  
  3. Array extend [
  4.     incAt: key [
  5.         ^self at: key put: (self at: key) + 1
  6.     ]
  7. ]
  8.  
  9. " Read and sort input "
  10. adapt := SortedCollection with: 1.
  11. stdin linesDo: [ :line | adapt add: (line asNumber + 1) ].
  12.  
  13. " Calculate difference counts "
  14. counts := Array withAll: #(0 0 1).
  15. (1 to: adapt size - 1) do: [ :i |
  16.     counts incAt: (adapt at: i+1) - (adapt at: i)
  17. ].
  18.  
  19. stdout nextPutAll: 'Part 1: ', ((counts at: 3) * (counts at: 1)) asString; nl.
  20.  
  21. " Part 2 -- Dynamic Programming "
  22. table := Array new: adapt last.
  23. table at: 1 put: 1.
  24.  
  25. " Progressively build table using previous calculated values "
  26. adapt do: [ :i |
  27.     ((table at: i) = nil) ifTrue: [
  28.         conx := adapt select: [ :a | a between: (i-3) and: (i-1) ].
  29.         sum  := conx inject: 0 into: [ :a :b | a + (table at: b) ].
  30.         table at: i put: sum.
  31.     ]
  32. ].
  33.  
  34. stdout nextPutAll: 'Part 2: ', table last asString; nl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement