Advertisement
musifter

AoC day 9, Smalltalk

Dec 9th, 2020
1,973
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/local/bin/gst -q
  2.  
  3. OrderedCollection extend [
  4.     canSum: num [
  5.         " XXX: cleaner way to do this? "
  6.         (0 to: self size - 2) do: [ :i |
  7.             (self readStream copyFrom: i + 1 to: self size - 1) do: [ :j |
  8.                 ((self at: i + 1) + j = num) ifTrue: [ ^true ]
  9.             ]
  10.         ].
  11.         ^false
  12.     ]
  13.  
  14.     findBadSum [
  15.         | rs targ window |
  16.         rs := ReadStream on: self.
  17.         window := (rs copyFrom: 0 to: 24).
  18.  
  19.         (rs position: 25) do: [ :next |
  20.             (window canSum: next) ifFalse: [ ^next ].
  21.             window removeFirst.
  22.             window addLast: next.
  23.         ].
  24.         ^nil
  25.     ]
  26.  
  27.     findSumRange: targ [
  28.         | i j sum |
  29.         i := 1.
  30.         j := 1.
  31.         sum := self at: 1.
  32.  
  33.         [ sum == targ ] whileFalse: [
  34.             (sum < targ) ifTrue: [ j := j + 1.  sum := sum + (self at: j) ].
  35.             (sum > targ) ifTrue: [ sum := sum - (self at: i).  i := i + 1 ].
  36.         ].
  37.  
  38.         ^Array with: i - 1 with: j - 1.
  39.     ]
  40. ]
  41.  
  42. "
  43. |  Mainline
  44. "
  45. list := OrderedCollection new.
  46. stdin linesDo: [ :line | list addLast: line asNumber ].
  47.  
  48. part1 := list findBadSum.
  49. stdout nextPutAll: ('Part 1: ', part1 asString); nl.
  50.  
  51. range    := list findSumRange: part1.
  52. interval := list readStream copyFrom: range first to: range second.
  53.  
  54. part2 := (interval inject: part1 into: [ :a :b | a min: b ])
  55.        + (interval inject: 0     into: [ :a :b | a max: b ]).
  56.  
  57. stdout nextPutAll: ('Part 2: ', part2 asString); nl.
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement