Advertisement
musifter

AoC 2022, day 25 (smalltalk)

Dec 25th, 2022
2,929
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 1.43 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. Array subclass: SnafuNumber [
  4.     <shape: #pointer>
  5.  
  6.     value := Dictionary from: { $= -> -2.  $- -> -1.  $0 -> 0.  $1 -> 1.  $2 -> 2 }.
  7.     char  := Dictionary from: { -2 -> $=.  -1 -> $-.  0 -> $0.  1 -> $1.  2 -> $2 }.
  8.  
  9.     SnafuNumber class >> fromString: str [ ^(super new: 32 withAll: 0) initString: str ]
  10.  
  11.     initString: str [
  12.         str reverse keysAndValuesDo: [:i :chr | self at: i put: (value at: chr)].
  13.         ^self
  14.     ]
  15.  
  16.     + other [
  17.         | res val |
  18.         res := SnafuNumber new: 32 withAll: 0.
  19.         (1 to: self size - 1) do: [ :i |
  20.             val := (self at: i) + (other at: i) + (res at: i).
  21.  
  22.             " do appropriate carry, if needed "
  23.             (val abs > 2) ifTrue: [
  24.                 res at: i+1 put: val sign.
  25.                 val := val - (5 * val sign).
  26.             ].
  27.  
  28.             res at: i put: val.
  29.         ].
  30.         ^res
  31.     ]
  32.  
  33.     printOn: aStream [
  34.         | printing |
  35.         printing := false.  " to ignore leading zeroes"
  36.  
  37.         self reverse do: [ :digit |
  38.             (printing or: [digit ~= 0]) ifTrue: [
  39.                 aStream nextPut: (char at: digit).
  40.                 printing := true.
  41.             ]
  42.         ].
  43.         (printing not) ifTrue: [ aStream nextPut: $0 ].
  44.     ]
  45. ]
  46.  
  47.  
  48. "
  49. | Mainline
  50. "
  51. input := stdin lines contents collect: [:line | SnafuNumber fromString: line].
  52. ('Part 1: %1' % {input fold: [:a :b | a + b]}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement