Advertisement
musifter

AoC day 14 (pt2), Smalltalk

Dec 14th, 2020
2,784
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/local/bin/gst -q
  2.  
  3. String extend [
  4.     asRadix: rad [
  5.         ^Number readFrom: (ReadStream on: self) radix: rad.
  6.     ]
  7. ]
  8.  
  9. Object subclass: MemoryTable [
  10.     | mem or_mask fl_mask |
  11.  
  12.     MemoryTable class >> new [
  13.         ^(super new) init
  14.     ]
  15.  
  16.     init [
  17.         mem := Dictionary new.
  18.         or_mask := 0.
  19.         fl_mask := 0.
  20.         ^self
  21.     ]
  22.  
  23.     setMask: mask [
  24.         or_mask := (mask copyReplaceAll: 'X' with: '0') asRadix: 2.
  25.         fl_mask := (mask collect: [:c | (c = $X) ifTrue: [$1] ifFalse: [$0]]) asRadix: 2.
  26.     ]
  27.  
  28.     at: addr put: val float: mask [
  29.         (mask = 0) ifTrue: [
  30.             mem at: addr put: val.
  31.         ] ifFalse: [
  32.             | bit next |
  33.             bit  := mask - (mask bitAnd: (mask - 1)).  " get lowest set bit "
  34.             next := mask bitXor: bit.                  " toggle bit off "
  35.  
  36.             self at: (addr bitAnd: bit bitInvert) put: val float: next.
  37.             self at: (addr bitOr: bit) put: val float: next.
  38.         ]
  39.     ]
  40.  
  41.     at: addr put: val [
  42.         self at: (addr bitOr: or_mask) put: val float: fl_mask.
  43.     ]
  44.  
  45.     checksum [
  46.         ^mem fold: [ :a :b | a + b ].
  47.     ]
  48. ]
  49.  
  50. "
  51. | Mainline
  52. "
  53. memory := MemoryTable new.
  54.  
  55. ((stdin contents tokenize: 'mask = ') reject: [:a | a size = 0]) do: [ :block |
  56.     cmds := (block tokenize: '\n') asOrderedCollection.
  57.  
  58.     mask := cmds removeFirst.
  59.     stdout nextPutAll: ('Mask: ', mask); cr; flush.
  60.     memory setMask: mask.
  61.  
  62.     cmds do: [ :set |
  63.         pair := set subStrings: 'mem[] ='.
  64.         memory at:  (pair first) asNumber put: (pair second) asNumber.
  65.     ].
  66. ].
  67.  
  68. stdout nl.
  69. ('Part 2: ', memory checksum asString) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement