Advertisement
musifter

AoC 2024 day 13 (smalltalk)

Dec 13th, 2024
62
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. Symbol extend       [ value: arg [^arg perform: self] ]
  4. Collection extend   [ sum [^self inject: 0 into: [:a :b | a + b]] ]
  5.  
  6. Object subclass: ClawMachine [
  7.     | a b target |
  8.  
  9.     ClawMachine class >> new: anArray  [^super new init: anArray]
  10.     init: array [
  11.         a := (array first @ array second).
  12.         b := (array third @ array fourth).
  13.  
  14.         target := ((array at: 5) @ array last).
  15.         ^self
  16.     ]
  17.  
  18.     " Adjust claw target by offset: "
  19.     adjustTarget: offset [target := target + offset]
  20.  
  21.     " Get cost in tokens to win (0 if no win possible): "
  22.     solveCost [
  23.         | a_num b_num denom |
  24.         a_num := (target x * b y) - (target y * b x).
  25.         b_num := (target y * a x) - (target x * a y).
  26.         denom := (a x * b y) - (a y * b x).
  27.  
  28.         (a_num \\ denom == 0) & (b_num \\ denom == 0) ifTrue: [
  29.             ^(3 * a_num / denom) + (b_num / denom).
  30.         ].
  31.         ^0
  32.     ]
  33. ]
  34.  
  35. "
  36. | Mainline
  37. "
  38. " Grab input as paragraphs, grab all numbers in each paragraph: "
  39. para  := stdin contents tokenize: '\n\n'.
  40. input := para collect: [:p | ((p tokenize: '[^0-9]') reject: #isEmpty) collect: #asNumber].
  41.  
  42. machines := input collect: [:m | ClawMachine new: m].
  43.  
  44. part1 := (machines collect: #solveCost) sum.
  45. part2 := (machines collect: [:m | (m adjustTarget: 10_000_000_000_000) solveCost]) sum.
  46.  
  47. ('Part 1: %1' % {part1}) displayNl.
  48. ('Part 2: %1' % {part2}) displayNl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement