musifter

AoC day 2, Smalltalk

Dec 2nd, 2021
753
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/local/bin/gst -q
  2.  
  3. " Class to handle position of sub for part 1 "
  4. Object subclass: Position [
  5.     | horz vert |
  6.  
  7.     Position class >> new [
  8.         ^(super new) init.
  9.     ]
  10.  
  11.     init [
  12.         horz := vert := 0.
  13.         ^self
  14.     ]
  15.  
  16.     forward: mag  [ horz := horz + mag ]
  17.     up: mag       [ vert := vert - mag ]
  18.     down: mag     [ vert := vert + mag ]
  19.  
  20.     result  [ ^horz * vert ]
  21. ]
  22.  
  23. " Subclass of above to handle part 2 "
  24. Position subclass: AimPosition [
  25.     | depth |
  26.     AimPosition class >> new [
  27.         ^(super new) init.
  28.     ]
  29.  
  30.     init [
  31.         super init.
  32.         depth := 0.  " vert is now aim, depth is the actual position "
  33.         ^self
  34.     ]
  35.  
  36.     forward: mag  [ super forward: mag. depth := mag * vert + depth ]
  37.  
  38.     result: part [
  39.         ^(part = 1) ifTrue: [super result] ifFalse: [horz * depth]
  40.     ]
  41. ]
  42.  
  43. "
  44. | Mainline
  45. "
  46. sub := AimPosition new.
  47.  
  48. stdin linesDo: [ :line |
  49.     " Parse command into keyword method symbol "
  50.     cmd := (line substrings first, ':') asSymbol.
  51.     mag := line substrings second asNumber.
  52.  
  53.     sub perform: cmd with: mag.
  54. ].
  55.  
  56. 1 to: 2 do: [ :part |
  57.     ('Part %1: %2' % {part. sub result: part}) displayNl.
  58. ]
  59.  
RAW Paste Data