Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- OrderedCollection extend [
- canSum: num [
- " XXX: cleaner way to do this? "
- (0 to: self size - 2) do: [ :i |
- (self readStream copyFrom: i + 1 to: self size - 1) do: [ :j |
- ((self at: i + 1) + j = num) ifTrue: [ ^true ]
- ]
- ].
- ^false
- ]
- findBadSum [
- | rs targ window |
- rs := ReadStream on: self.
- window := (rs copyFrom: 0 to: 24).
- (rs position: 25) do: [ :next |
- (window canSum: next) ifFalse: [ ^next ].
- window removeFirst.
- window addLast: next.
- ].
- ^nil
- ]
- findSumRange: targ [
- | i j sum |
- i := 1.
- j := 1.
- sum := self at: 1.
- [ sum == targ ] whileFalse: [
- (sum < targ) ifTrue: [ j := j + 1. sum := sum + (self at: j) ].
- (sum > targ) ifTrue: [ sum := sum - (self at: i). i := i + 1 ].
- ].
- ^Array with: i - 1 with: j - 1.
- ]
- ]
- "
- | Mainline
- "
- list := OrderedCollection new.
- stdin linesDo: [ :line | list addLast: line asNumber ].
- part1 := list findBadSum.
- stdout nextPutAll: ('Part 1: ', part1 asString); nl.
- range := list findSumRange: part1.
- interval := list readStream copyFrom: range first to: range second.
- part2 := (interval inject: part1 into: [ :a :b | a min: b ])
- + (interval inject: 0 into: [ :a :b | a max: b ]).
- stdout nextPutAll: ('Part 2: ', part2 asString); nl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement