Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- Symbol extend [ value: obj [^obj perform: self] ]
- Integer extend [ oneBitSet [^(self bitAnd: (self - 1)) = 0] ]
- Collection extend [ reduceAsBinary [^self inject: 0 into: [:num :dig | num*2 + dig]] ]
- Array extend [
- " Method for finding index of reflection line in part 1: "
- findMirrorIndex [
- | stack |
- stack := OrderedCollection with: (self first).
- self allButFirst keysAndValuesDo: [:i :val |
- (val = stack last) ifTrue: [ stack removeLast ]
- ifFalse: [ stack add: val ].
- (stack isEmpty) ifTrue: [ ^(i+1) / 2 ]
- ].
- ^0
- ]
- " Method for finding index of reflection line in part 2: "
- findSmudgedIndex [
- | check pushVal popVal back |
- (1 to: self size // 2) do: [:depth |
- back := depth * 2 + 1.
- check := 0.
- (1 to: depth) do: [:i |
- pushVal := self at: i.
- popVal := self at: back - i.
- (pushVal ~= popVal) ifTrue: [
- " add one if 1 bit, 2 if more "
- check := check + ((pushVal bitXor: popVal) oneBitSet ifTrue: [1]
- ifFalse: [2]).
- ].
- ].
- " Check equals 1 only when exactly one 1-bit difference is seen "
- (check = 1) ifTrue: [ ^depth ].
- ].
- ^0
- ]
- " Scoring for problem: "
- score [ ^100 * self first + self second ]
- scanForMirrors: symMethod [
- | score |
- " Try backwards mirrors: "
- score := ((self collect: #reverse) collect: [:list | |val|
- val := list perform: symMethod.
- (val ~= 0) ifTrue: [ list size - val ] ifFalse: [0].
- ]) score.
- " Try forwards mirrors: "
- score := score + (self collect: symMethod) score.
- ^score
- ]
- ]
- "
- | Mainline
- "
- input := stdin contents tokenize: '\n\n'.
- grids := input collect: [:grid |
- (grid tokenize: '\n') collect: [:line |
- line asArray collect: [:chr | (chr = $#) ifTrue: [1] ifFalse: [0]].
- ]
- ].
- part1 := 0.
- part2 := 0.
- grids do: [:grid |
- " dimArrays has two elements: array of rows and array of cols "
- dimArrays := {
- " Parse rows as binary numbers: "
- grid collect: #reduceAsBinary.
- " Parse cols as binary numbers: "
- (1 to: grid first size) collect: [:col |
- (grid collect: [:row | row at: col]) reduceAsBinary
- ].
- }.
- part1 := part1 + (dimArrays scanForMirrors: #findMirrorIndex).
- part2 := part2 + (dimArrays scanForMirrors: #findSmudgedIndex).
- ].
- ('Part 1: %1' % {part1}) displayNl.
- ('Part 2: %1' % {part2}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement