Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- "
- | Class for handling a 2D array Grid
- "
- Object subclass: Grid [
- | dim_x dim_y rows changes |
- Grid class >> new [
- ^(super new) init
- ]
- init [
- changes := OrderedCollection new.
- rows := OrderedCollection new.
- dim_x := 0.
- dim_y := 0.
- ^self
- ]
- " loading method "
- addRow: str [
- rows addLast: str.
- dim_y := dim_y + 1.
- (dim_x = 0) ifTrue: [ dim_x := str size ].
- ^self
- ]
- " access methods "
- changes [ ^changes size ]
- at: pt [
- ^(rows at: pt y) at: pt x.
- ]
- at: pt put: val [
- ^(rows at: pt y) at: pt x put: val.
- ]
- " iterator methods "
- do: aBlock [
- rows do: [ :y |
- y do: [ :x |
- aBlock value: x
- ]
- ]
- ]
- doPoint: aBlock [
- (1 to: dim_y) do: [ :y |
- (1 to: dim_x) do: [ :x |
- aBlock value: (x @ y)
- ]
- ]
- ]
- inject: val into: aBlock [
- | ret |
- ret := val.
- self do: [ :b | ret := aBlock value: ret value: b ].
- ^ret
- ]
- from: pt1 to: pt2 inject: val into: aBlock [
- | ret |
- ret := val.
- (pt1 y to: pt2 y) do: [ :y |
- (pt1 x to: pt2 x) do: [ :x |
- ret := aBlock value: ret value: (self at: (x @ y)).
- ]
- ].
- ^ret
- ]
- neighbours: pt inject: val into: aBlock [
- | pt1 pt2 |
- pt1 := ((pt x - 1) max: 1) @ ((pt y - 1) max: 1).
- pt2 := ((pt x + 1) min: dim_x) @ ((pt y + 1) min: dim_y).
- ^self from: pt1 to: pt2 inject: val into: aBlock
- ]
- " methods for marking changes and applying them "
- mark: pt put: val [
- changes add: (Array with: pt with: val).
- ]
- applyChanges [
- changes do: [ :ch |
- self at: ch first put: ch second.
- ].
- changes empty.
- ]
- " output method "
- printOn: stream [
- rows do: [ :line |
- stream nextPutAll: line; nl.
- ]
- ]
- ]
- "
- | Mainline
- "
- grid := Grid new.
- stdin linesDo: [ :line |
- grid addRow: line.
- ].
- grid printNl.
- gen := 1.
- [ (grid changes > 0) or: [ gen = 1 ] ] whileTrue: [
- stdout nextPutAll: 'Generation: ', gen asString,
- ' Changes: ', grid changes asString, ' ';
- cr; flush.
- grid applyChanges.
- gen := gen + 1.
- grid doPoint: [ :pt |
- occ := grid neighbours: pt
- inject: 0
- into: [:a :b | a + ((b == $#) asCBooleanValue)].
- cell := grid at: pt.
- ((cell == $#) and: [occ >= 5]) ifTrue: [ grid mark: pt put: $L ].
- ((cell == $L) and: [occ = 0]) ifTrue: [ grid mark: pt put: $# ].
- ].
- ].
- grid printNl.
- part1 := grid inject: 0 into: [ :a :b | a + ((b == $#) asCBooleanValue) ].
- stdout nl; nextPutAll: 'Part 1: ', part1 asString; nl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement