Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- LookupTable extend [
- incAt: key [
- ^self at: key put: (self at: key ifAbsent: [0]) + 1.
- ]
- ]
- Object subclass: HexGrid [
- | hexgrid black_tiles |
- HexGrid class >> new [
- Dirs := LookupTable new.
- Dirs at: #e put: ( 0 @ 1); at: #ne put: ( 1 @ 0); at: #nw put: ( 1 @ -1);
- at: #w put: ( 0 @ -1); at: #sw put: (-1 @ 0); at: #se put: (-1 @ 1).
- ^(super new) init
- ]
- HexGrid class >> neighbours: cell [
- ^Dirs collect: [ :d | cell + d ]
- ]
- HexGrid class >> dirs [
- ^Dirs
- ]
- init [
- hexgrid := LookupTable new.
- black_tiles := OrderedCollection new.
- ^self
- ]
- flip: cell [
- | hash |
- hexgrid at: cell put: (hexgrid at: cell ifAbsentPut: [false]) not.
- ]
- count_flipped [
- hexgrid keysDo: [ :cell | (hexgrid at: cell) ifTrue: [ black_tiles add: cell ] ].
- ^black_tiles size.
- ]
- run_life: turns [
- | black_adj count next |
- black_adj := LookupTable new.
- black_tiles do: [ :cell |
- black_adj at: cell ifAbsentPut: [0].
- (HexGrid neighbours: cell) do: [ :neigh | black_adj incAt: neigh ]
- ].
- count := black_tiles size.
- (1 to: turns) do: [ :time |
- next := LookupTable new.
- black_adj associationsDo: [ :tile |
- (hexgrid at: tile key ifAbsentPut: [false]) ifTrue: [
- " black case "
- ((tile value = 0) or: [tile value > 2]) ifTrue: [
- self flip: tile key.
- count := count - 1.
- ]
- ] ifFalse: [
- " white case "
- (tile value = 2) ifTrue: [
- self flip: tile key.
- count := count + 1.
- ]
- ].
- (hexgrid at: tile key) ifTrue: [
- next at: tile key ifAbsentPut: [0].
- (HexGrid neighbours: tile key) do: [ :neigh | next incAt: neigh ]
- ]
- ].
- stdout nextPutAll: ('Time ', time asString, ' = ', count asString, ' '); cr; flush.
- black_adj := next.
- ].
- stdout nl.
- ]
- ]
- "
- | Mainline
- "
- grid := HexGrid new.
- stdin linesDo: [ :line |
- hex := (0 @ 0).
- ns_seen := ''.
- line do: [ :chr |
- ((chr = $n) or: [chr = $s]) ifTrue: [
- ns_seen := chr asString.
- ] ifFalse: [
- hex := hex + (HexGrid dirs at: (ns_seen, chr asString) asSymbol).
- ns_seen := ''.
- ].
- ].
- grid flip: hex.
- ].
- stdout nextPutAll: ('Part 1: ', grid count_flipped asString); nl.
- grid run_life: 100.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement