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 ifAbsent: [0]) + 1) ]
- ]
- "
- | Class to handle the 2D Grid
- "
- Object subclass: DigitGrid [
- | grid xsize |
- dirs := { (-1@-1). (-1@ 0). (-1@ 1).
- ( 0@-1). ( 0@ 1).
- ( 1@-1). ( 1@ 0). ( 1@ 1) }.
- DigitGrid class >> new: arrayStrings [
- ^(super new) init: arrayStrings.
- ]
- init: mapArray [
- xsize := (mapArray at: 1) size.
- grid := Array from: (mapArray collect: [:line |
- line asArray apply: #digitValue
- ]).
- ^self
- ]
- " Access to grid by Points "
- at: pt [
- ^(grid at: pt y) at: pt x
- ]
- at: pt put: chr [
- ^(grid at: pt y) at: pt x put: chr
- ]
- incAt: pt [
- ^self at: pt put: ((self at: pt) + 1)
- ]
- " Get coordinates of neighbours "
- neighbours: pt [
- ^(dirs collect: [:d | pt + d ]) select: [:n |
- (n x between: 1 and: xsize) & (n y between: 1 and: grid size)
- ]
- ]
- " Execute a block on every Point of our input "
- pointDo: aBlock [
- (1 to: grid size) do: [ :y |
- (1 to: xsize) do: [ :x |
- aBlock value: (x@y)
- ]
- ]
- ]
- ]
- "
- | Mainline
- "
- grid := DigitGrid new: stdin lines contents.
- time := 0.
- flashes := 0.
- [
- flashed := Dictionary new.
- queue := OrderedCollection new.
- grid pointDo: [:pt | ((grid incAt: pt) = 10) ifTrue: [queue add: pt]].
- [ queue notEmpty ] whileTrue: [
- | pos |
- pos := queue removeFirst.
- ((flashed incAt: pos) = 1) ifTrue: [
- (grid neighbours: pos) do: [ :pt |
- ((grid incAt: pt) = 10) ifTrue: [queue add: pt]
- ]
- ]
- ].
- flashes := flashes + flashed keys size.
- flashed keys do: [:pt | grid at: pt put: 0].
- ((time := time + 1) = 100) ifTrue: [
- ('Part 1: %1' % {flashes}) displayNl.
- ].
- (flashed keys size < 100)
- ] whileTrue.
- ('Part 2: %1' % {time}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement