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] ]
- incAt: idx [ ^self at: idx put: ((self at: idx) + 1) ]
- ]
- Object subclass: Card [
- | score numbers lines |
- Card class >> new: string [
- ^(super new) init: string
- ]
- init: string [
- score := 0. " sum of numbers left"
- lines := Array new: 10 withAll: 0. " num squares marked in line "
- numbers := Dictionary new. " map number to its lines (row, col) "
- " Parse card "
- string lines keysAndValuesDo: [ :y :row |
- (row substrings apply: #asNumber) keysAndValuesDo: [ :x :n |
- score := score + n.
- numbers at: n put: { x. 5 + y }
- ]
- ].
- ^self
- ]
- call: num [
- (numbers includesKey: num) ifTrue: [
- score := score - num.
- (numbers at: num) do: [ :linenum |
- ((lines incAt: linenum) = 5) ifTrue: [
- ^score * num
- ]
- ]
- ].
- ^nil
- ]
- ]
- "
- | Mainline
- "
- sections := stdin contents tokenize: '\n\n'.
- calls := (sections first tokenize: ',') apply: #asNumber.
- cards := Set from: (sections allButFirst collect: [:block | Card new: block]).
- first := true.
- calls do: [ :num |
- cards do: [ :card |
- score := card call: num.
- (score) ifNotNil: [
- (first) ifTrue: [
- ('Part 1: %1' % {score}) displayNl.
- first := false
- ].
- cards remove: card.
- (cards isEmpty) ifTrue: [
- ('Part 2: %1' % {score}) displayNl
- ]
- ]
- ]
- ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement