Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- Collection extend [
- apply: method [ ^self collect: [:x | x perform: method] ]
- sum [ ^self inject: 0 into: [:a :b | a + b] ]
- product [ ^self inject: 1 into: [:a :b | a * b] ]
- ]
- SequenceableCollection extend [
- " Return a list of ranges of the indices where aBlock is true "
- findRanges: aBlock [
- | res start |
- res := OrderedCollection new.
- start := 0.
- self keysAndValuesDo: [:i :item |
- (aBlock value: item) ifTrue: [
- (start = 0) ifTrue: [ start := i ]
- ] ifFalse: [
- (start ~= 0) ifTrue: [ res add: (start to: i - 1). start := 0 ].
- ]
- ].
- (start ~= 0) ifTrue: [ res add: (start to: self size) ].
- ^res
- ]
- ]
- "
- | Mainline
- "
- " Load input into OrderedCollection of Strings, adding sentinel ring of . "
- grid := (stdin lines contents collect: [:line | '.', line, '.']) asOrderedCollection.
- grid addFirst: ($. * grid first size);
- addLast: ($. * grid first size).
- part1 := 0.
- gears := Dictionary new.
- " Scan grid "
- grid keysAndValuesDo: [ :y :line |
- (line findRanges: [:c | c isDigit]) do: [ :part |
- | range box num foundPart |
- num := (line atAll: part) asNumber.
- range := part first - 1 to: part last + 1.
- " Get the surrounding box for our found number: "
- box := (y-1 to: y+1) collect: [:i | ((grid at: i) atAll: range)].
- foundPart := false.
- box keysAndValuesDo: [ :i :row |
- row keysAndValuesDo: [ :j :chr |
- " Any part symbol means this is a valid part number: "
- (chr isDigit not & (chr ~= $.)) ifTrue: [
- foundPart := true.
- ].
- " For gears, add part number to list (tracked by gear location)"
- (chr = $*) ifTrue: [
- (gears at: (y + i - 1) @ (range first + j)
- ifAbsentPut: [OrderedCollection new]) add: num.
- ].
- ]
- ].
- foundPart ifTrue: [ part1 := part1 + num ].
- ]
- ].
- " Valid gears have only two numbers adjacent, multiply those for ratio and sum "
- part2 := ((gears select: [:g | g size = 2]) apply: #product) sum.
- ('Part 1: %1' % {part1}) displayNl.
- ('Part 2: %1' % {part2}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement