Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- Collection extend [
- apply: method [ ^self collect: [:x | x perform: method] ]
- sum [ ^self inject: 0 into: [:a :b | a + b] ]
- ]
- String extend [
- " Return number made from first and last digit in string "
- firstLastNumber [
- | digits |
- digits := self select: [:c | c isDigit].
- ^10 * digits first digitValue + digits last digitValue.
- ]
- " Return true if first n characters match last n of str "
- first: n matchLast: str [ ^(self first: n) = (str last: n) ]
- " For a list of associations, do search/replace of key for value in order "
- copyReplaceList: list [
- ^list inject: self into: [:str :rule |
- str copyReplaceAll: rule key with: rule value
- ].
- ]
- ]
- " Build replacement table from names of numbers "
- numbers := {'one'. 'two'. 'three'. 'four'. 'five'. 'six'. 'seven'. 'eight'. 'nine'}.
- " Make list of search/replacement commands that maintains all possible overlaps "
- replacements := OrderedCollection new.
- numbers keysAndValuesDo: [:val :num |
- | pre suf |
- pre := 0.
- suf := 0.
- (numbers reject: [:n | n = num]) do: [:str |
- | lens |
- lens := (num size min: str size) to: 1 by: -1.
- pre := pre max: (lens findFirst: [:len | num first: len matchLast: str]).
- suf := suf max: (lens findFirst: [:len | num first: len matchLast: str]).
- ].
- " Pattern: longest prefix needed, digit, longest suffix needed "
- replacements add: num -> ((num first: pre), val asString, (num last: suf)).
- ].
- input := stdin lines contents.
- convert := input collect: [ :line | line copyReplaceList: replacements ].
- ('Part 1: %1' % {(input apply: #firstLastNumber) sum}) displayNl.
- ('Part 2: %1' % {(convert apply: #firstLastNumber) sum}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement