Advertisement
musifter

AoC 2022, day 2 (smalltalk)

Dec 2nd, 2022
2,325
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Smalltalk 2.23 KB | Source Code | 0 0
  1. #!/usr/local/bin/gst -q
  2.  
  3. Array extend [
  4.     " Extension for Array for simple vector addition "
  5.     + arr [ ^self with: arr collect: [:a :b | a + b] ]
  6.  
  7.     " Increment value in array at idx by val "
  8.     at: idx inc: val [ ^self at: idx put: ((self at: idx) + val) ]
  9. ]
  10.  
  11. "
  12. | Okay, being a bit silly with the solution on this one to make something
  13. | different from my other solutions.  In this one we're going to take
  14. | advantage of the the fact that the 3x3 table of (elf moves x repsonses)
  15. | has all nine scores from 1 to 9 in its cells.  And for both parts there's
  16. | a fairly simple path to walk those cells from 1 to 9.
  17. "
  18. Object subclass: RPSWalker [
  19.     | coord |
  20.     RPSWalker class >> new: pair [
  21.         ^(super new) init: pair
  22.     ]
  23.  
  24.     init: pair [
  25.         " Pair comes in as ASCII string, we want values on [0,2] for mod "
  26.         coord := {pair first asInteger - 65. pair second asInteger - 88}.
  27.         ^self
  28.     ]
  29.  
  30.     + step [
  31.         " Add step using mod to wrap around the table as needed "
  32.         coord := (coord + step) collect: [:x | x \\ 3]
  33.     ]
  34.  
  35.     coord [
  36.         " Give our coord back as the same type of string we orginially got "
  37.         ^String from: {(coord first + 65) asCharacter. (coord second + 88) asCharacter}
  38.     ]
  39. ]
  40.  
  41. "
  42. | Mainline
  43. "
  44. " First off... lets just collect all the moves in a bag as order doesn't matter "
  45. turns := Bag from: (stdin contents lines collect: [:x | x substrings join]).
  46.  
  47. sum    := { 0. 0 }.
  48. walker := { RPSWalker new: 'BX'. RPSWalker new: 'BX' }.  " both start at this cell "
  49.  
  50. " Walk the tables "
  51. 1 to: 9 do: [ :score |
  52.     1 to: 2 do: [:part |
  53.        | step |
  54.         " add number in bag * current score iterator to our sum "
  55.         sum at: part inc: (turns occurrencesOf: (walker at: part) coord) * score.
  56.  
  57.         " Every third step in both parts is just a shift to right. "
  58.         " In part 1, the other steps are diagonally down-right, "
  59.         " and in part 2, they're just straight down. "
  60.         step := ((score \\ 3) = 0) ifTrue:  [{0. 1}]
  61.                                    ifFalse: [{1. part \\ 2}].
  62.         walker at: part inc: step.
  63.     ].
  64. ].
  65.  
  66. " Output results "
  67. sum keysAndValuesDo: [:part :res |
  68.     ('Part %1: %2' % {part. res}) displayNl.
  69. ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement