Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- Symbol extend [ value: arg [^arg perform: self] ]
- Object subclass: TextGrid [
- | grid dim robot |
- dirs := Dictionary from: {$< -> (-1@0). $^ -> (0@-1). $v -> (0@1). $> -> (1@0)}.
- TextGrid class >> new: mapArray [^super new init: mapArray]
- init: mapArray [
- " No sentinel needed, has boundary wall."
- dim := (mapArray first size @ mapArray size).
- grid := mapArray join.
- robot := grid indexOfSubCollection: '@'.
- grid at: robot put: $..
- robot := self toCoord: robot.
- ^self
- ]
- " Access to grid via Points "
- at: pt [^grid at: (pt y * dim x) + pt x + 1]
- at: pt put: chr [^grid at: (pt y * dim x) + pt x + 1 put: chr]
- toCoord: idx [^(idx - 1 \\ dim x) @ (idx - 1 // dim x)]
- toIndex: pt [^(pt y * dim x) + pt x + 1]
- " Basic access "
- dirs [^dirs]
- dim [^dim]
- robot [^robot]
- robot: pt [^robot := pt]
- " Return array of Points where aBlock on that character returns true "
- selectPoints: aBlock [
- | res |
- res := OrderedCollection new.
- grid keysAndValuesDo: [:idx :chr |
- (aBlock value: chr) ifTrue: [res add: (self toCoord: idx)].
- ].
- ^res
- ]
- " Print grid on stream "
- printOn: aStream [
- | robotIdx |
- robotIdx := self toIndex: robot.
- grid keysAndValuesDo: [:idx :chr |
- aStream nextPut: (idx == robotIdx ifTrue: [$@] ifFalse: [chr]).
- (idx \\ dim x = 0) ifTrue: [aStream nl].
- ]
- ]
- ]
- "
- | Mainline
- "
- sections := (stdin contents tokenize: '\n\n') collect: #lines.
- grid := TextGrid new: sections first.
- sections second join do: [ :dchr |
- dir := grid dirs at: dchr.
- move := grid robot + dir.
- targ := grid at: move.
- (targ == $O) ifTrue: [
- end := move.
- [(grid at: end) == $O] whileTrue: [end := end + dir].
- ((grid at: end) == $.) ifTrue: [
- grid at: end put: $O.
- grid at: move put: $..
- grid robot: move.
- ]
- ] ifFalse: [
- (targ == $.) ifTrue: [grid robot: move] "$# does noting"
- ].
- ].
- grid displayNl.
- part1 := (grid selectPoints: [:chr | chr == $O]) inject: 0 into: [:a :b| a + (100 * b y) + b x].
- ('Part 1: %1' % {part1}) displayNl.
Add Comment
Please, Sign In to add comment