Advertisement
musifter

AoC 2021 day 5 (smalltalk, sets p2)

Dec 5th, 2021
2,183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/local/bin/gst -q
  2.  
  3. Collection extend [
  4.     apply: method  [ ^self collect: [:x | x perform: method] ]
  5.     incAt: idx     [ ^self at: idx put: ((self at: idx) + 1) ]
  6. ]
  7.  
  8. Set subclass: LineSet [
  9.     <shape: #pointer>
  10.  
  11.     LineSet class >> from: pt1 to: pt2 [
  12.         ^(super new) start: pt1 end: pt2
  13.     ]
  14.  
  15.     start: s end: e [
  16.         | start end step pos |
  17.         start := s y * 1000 + s x + 1.
  18.         end   := e y * 1000 + e x + 1.
  19.         step  := (e y - s y) sign * 1000 + (e x - s x) sign.
  20.         pos   := start.
  21.  
  22.         self add: pos.
  23.         [pos = end] whileFalse: [
  24.             pos := pos + step.
  25.             self add: pos.
  26.         ].
  27.  
  28.         ^self
  29.     ]
  30. ]
  31.  
  32. " Recursive divide and conquer to apply set arithmetic "
  33. div_and_conq := [ :lines |
  34.    | half res1 res2 union intersect |
  35.  
  36.     (lines size = 1) ifTrue: [
  37.         { Set from: lines first. Set new }
  38.     ] ifFalse: [
  39.         half := lines size // 2.
  40.  
  41.         res1 := div_and_conq value: (lines atAll: (1 to: half)).
  42.         res2 := div_and_conq value: (lines atAll: (half + 1 to: lines size)).
  43.  
  44.         union := res1 first + res2 first.
  45.         intersect := res1 second + res2 second + (res1 first & res2 first).
  46.         { union. intersect }
  47.     ]
  48. ].
  49.  
  50. "
  51. | Mainline
  52. "
  53. ObjectMemory spaceGrowRate: 500.0.
  54.  
  55. lines := stdin lines contents collect: [ :str |
  56.              nums := (str subStrings: ', ->') apply: #asNumber.
  57.              LineSet from: (nums first @ nums second) to: (nums third @ nums fourth).
  58.          ].
  59.  
  60. res := div_and_conq value: lines.
  61.  
  62. ('Part 2: %1' % {res second size}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement