Advertisement
musifter

AoC 2023, day 1 (smalltalk)

Dec 1st, 2023
1,603
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 1.81 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. Collection extend [
  4.     apply: method  [ ^self collect: [:x | x perform: method] ]
  5.     sum            [ ^self inject: 0 into: [:a :b | a + b]   ]
  6. ]
  7.  
  8. String extend [
  9.     " Return number made from first and last digit in string "
  10.     firstLastNumber [
  11.         | digits |
  12.         digits := self select: [:c | c isDigit].
  13.         ^10 * digits first digitValue + digits last digitValue.
  14.     ]
  15.  
  16.     " Return true if first n characters match last n of str "
  17.     first: n matchLast: str  [ ^(self first: n) = (str last: n) ]
  18.  
  19.     " For a list of associations, do search/replace of key for value in order "
  20.     copyReplaceList: list [
  21.         ^list inject: self into: [:str :rule |
  22.             str copyReplaceAll: rule key with: rule value
  23.         ].
  24.     ]
  25. ]
  26.  
  27. " Build replacement table from names of numbers "
  28. numbers := {'one'. 'two'. 'three'. 'four'. 'five'. 'six'. 'seven'. 'eight'. 'nine'}.
  29.  
  30. " Make list of search/replacement commands that maintains all possible overlaps "
  31. replacements := OrderedCollection new.
  32. numbers keysAndValuesDo: [:val :num |
  33.    | pre suf |
  34.     pre := 0.
  35.     suf := 0.
  36.     (numbers reject: [:n | n = num]) do: [:str |
  37.        | lens |
  38.         lens := (num size min: str size) to: 1 by: -1.
  39.         pre := pre max: (lens findFirst: [:len | num first: len matchLast: str]).
  40.         suf := suf max: (lens findFirst: [:len | num first: len matchLast: str]).
  41.     ].
  42.  
  43.     " Pattern: longest prefix needed, digit, longest suffix needed "
  44.     replacements add: num -> ((num first: pre), val asString, (num last: suf)).
  45. ].
  46.  
  47. input   := stdin lines contents.
  48. convert := input collect: [ :line | line copyReplaceList: replacements ].
  49.  
  50. ('Part 1: %1' % {(input   apply: #firstLastNumber) sum}) displayNl.
  51. ('Part 2: %1' % {(convert apply: #firstLastNumber) sum}) displayNl.
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement