Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- Object subclass: TextGrid [
- | grid dimX dimY |
- " Directions: order is important for diags to work "
- dirs := {(-1 @ -1). ( 0 @ -1). ( 1 @ -1).
- (-1 @ 0). ( 1 @ 0).
- (-1 @ 1). ( 0 @ 1). ( 1 @ 1)}.
- TextGrid class >> dirs [^dirs]
- TextGrid class >> diags [^dirs atAll: #(1 3 6 8)]
- TextGrid class >> new: mapArray [
- ^super new init: mapArray
- ]
- init: mapArray [
- | sentinel |
- dimY := mapArray size + 2.
- dimX := mapArray first size + 2.
- " Add sentinels to all sides "
- sentinel := (1 to: dimX) inject: '' into: [:a :b | a, '.'].
- grid := sentinel, (mapArray collect: [:row | '.', row, '.']) join, sentinel.
- ^self
- ]
- " Access to grid via Points "
- at: pt [^grid at: (pt y * dimX) + pt x + 1]
- at: pt put: chr [^grid at: (pt y * dimX) + pt x + 1 put: chr]
- " Return array of Points where aBlock on that character returns true "
- selectPoints: aBlock [
- | res |
- res := OrderedCollection new.
- (1 to: dimY - 1) do: [:y |
- (1 to: dimX - 1) do: [:x |
- (aBlock value: (self at: x @ y)) ifTrue: [res add: x @ y].
- ]
- ].
- ^res
- ]
- ]
- "
- | Mainline
- "
- grid := TextGrid new: stdin lines contents.
- " Part 1 "
- part1 := 0.
- (grid selectPoints: [:chr | chr == $X]) do: [:pt |
- part1 := part1 + (TextGrid dirs count: [:d |
- (1 to: 3) conform: [:i | (grid at: (d * i + pt)) == ('MAS' at: i)]
- ]).
- ].
- ('Part 1: %1' % {part1}) displayNl.
- " Part 2 "
- part2 := 0.
- (grid selectPoints: [:chr | chr == $A]) do: [:pt |
- corners := TextGrid diags collect: [:d | grid at: pt + d].
- ((corners conform: [:c | (c == $M) | (c == $S)])
- & (corners first ~= corners fourth)
- & (corners second ~= corners third)) ifTrue: [ part2 := part2 + 1 ].
- ].
- ('Part 2: %1' % {part2}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement