musifter

AoC 2025, day 5 (Smalltalk)

Dec 5th, 2025
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 1.35 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. Symbol extend     [ value: arg [^arg perform: self] ]
  4.  
  5. Collection extend [ sum [^self inject: 0 into: [:a :b | a + b]] ]
  6.  
  7. String extend [
  8.     " Interpret (\d+)-(\d+) string as an Interval "
  9.     asInterval [
  10.         | range |
  11.         range := (self subStrings: '-') collect: [:n | n asInteger].
  12.         ^Interval from: range first to: range second.
  13.     ]
  14. ]
  15.  
  16. Interval extend [
  17.     " Get intersection of self and another Interval "
  18.     & other [ ^(self first max: other first) to: (self last min: other last) ]
  19.     " Get union of self and another Interval (ASSUMES: intersecting)"
  20.     + other [ ^(self first min: other first) to: (self last max: other last) ]
  21. ]
  22.  
  23. "
  24. | Mainline
  25. "
  26. sections := (stdin contents tokenize: '\n\n') collect: #lines.
  27.  
  28. ranges := sections first  collect: #asInterval.
  29. food   := sections second collect: #asNumber.
  30.  
  31. " Part 1: "
  32. part1 := food count: [:id | ranges contains: [:r | id between: r first and: r last]].
  33. ('Part 1: %1' % {part1}) displayNl.
  34.  
  35. " Part 2: "
  36. merged := OrderedCollection new.
  37.  
  38. ranges do: [:r |
  39.     curr := r.
  40.     next := OrderedCollection new.
  41.     merged do: [:o |
  42.         ((r & o) size > 0) ifTrue:  [ curr := curr + o ]
  43.                            ifFalse: [ next add: o ].
  44.     ].
  45.  
  46.     merged := next, {curr}.
  47. ].
  48.  
  49. ('Part 2: %1' % {(merged collect: #size) sum}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment