Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- String extend [
- asRadix: rad [ ^Number readFrom: (ReadStream on: self) radix: rad ]
- ]
- Character extend [
- " Extension to Character to handle paired delimiters "
- pairs := Dictionary from: { $( -> $). $[ -> $]. ${ -> $}. $< -> $> }.
- isOpen [ ^pairs includesKey: self ]
- closedBy [ ^pairs at: self ]
- ]
- " Error class to throw on syntax errors... holds and scores token "
- Error subclass: SyntaxError [
- | token |
- table := Dictionary from: { $) -> 3. $] -> 57. $} -> 1197. $> -> 25137 }.
- SyntaxError class >> on: chr [
- ^super new init: chr
- ]
- init: chr [
- token := chr.
- ^self
- ]
- score [
- ^table at: token
- ]
- ]
- "
- | Mainline
- "
- part1 := 0.
- part2 := SortedCollection new.
- stdin linesDo: [ :line |
- stack := OrderedCollection new.
- [
- line do: [ :chr |
- (chr isOpen) ifTrue: [
- stack addFirst: chr closedBy
- ] ifFalse: [
- (chr ~= stack removeFirst) ifTrue: [(SyntaxError on: chr) signal]
- ]
- ]
- ] on: SyntaxError do: [ :sig |
- part1 := part1 + sig score.
- stack empty " corrupt, nothing to autocomplete "
- ].
- " autocomplete if needed: "
- (stack notEmpty) ifTrue: [
- part2 add: ((stack gather: [:c | (')]}>' indexOf: c) asString]) asRadix: 5).
- ]
- ].
- ('Part 1: %1' % {part1}) displayNl.
- ('Part 2: %1' % {part2 at: (part2 size // 2 + 1)}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement