Advertisement
musifter

AoC 2024, day 19 (smalltalk)

Dec 19th, 2024 (edited)
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 1.11 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. Collection extend   [ sum  [^self inject: 0 into: [:a :b | a + b]] ]
  4.  
  5. Object subclass: TowelPatternMatcher [
  6.     | towels memo |
  7.  
  8.     TowelPatternMatcher class >> new: array  [^super new init: array]
  9.     init: array  [
  10.         towels := array.
  11.         memo   := Dictionary from: {'' -> 1}.  " String perfectly matched "
  12.         ^self
  13.     ]
  14.  
  15.     countPatterns: str [
  16.         | ret |
  17.         ^memo at: str ifAbsentPut: [
  18.             ret := 0.
  19.             towels do: [:patt |
  20.                 (str startsWith: patt) ifTrue: [
  21.                     ret := ret + (self countPatterns: (str allButFirst: patt size)).
  22.                 ]
  23.             ].
  24.             ret
  25.         ]
  26.     ]
  27. ]
  28.  
  29. "
  30. | Mainline
  31. "
  32. sections := stdin contents tokenize: '\n\n'.
  33. matcher  := TowelPatternMatcher new: (sections first substrings: ', ').
  34.  
  35. " Adding output to show its working because this is slow: "
  36. counts   := (sections second substrings) collect: [:patt | (matcher countPatterns: patt) displayNl].
  37.  
  38. ('Part 1: %1' % {counts count: [:i | i ~= 0]}) displayNl.
  39. ('Part 2: %1' % {counts sum}) displayNl.
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement