Guest User

Untitled

a guest
Dec 12th, 2024
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. # Input: lines like
  2. #          Button A: X+#, Y+#
  3. #          Button B: X+#, Y+#
  4. #          Prize: X=#, Y=# (add 10 trillion to each)
  5. #        separated by blank lines
  6. # Output: if it costs 3 tokens to push A and 1 to push B,
  7. #         what's the cheapest way to get from 0, 0 to prize location?
  8. #         total cost across all sets of three lines
  9.  
  10. def get_cheapest_cost(ax, ay, bx, by, px, py):
  11.   # ax*na + bx*nb = px
  12.   # ay*na + by*nb = py
  13.   # thus
  14.   # ay*ax*na + ay*bx*nb = ay*px
  15.   # ax*ay*na + ax*by*nb = ax*py
  16.   # thus
  17.   # (ay*bx - ax*by)*nb = ay*px - ax*py
  18.   nb = int((ay*px - ax*py) / (ay*bx - ax*by))
  19.   na = int((px - nb*bx) / ax)
  20.   if (na * ax) + (nb * bx) == px and (na * ay) + (nb * by) == py:
  21.     return 3 * na + nb
  22.   return -1
  23.  
  24. button_a = []
  25. button_b = []
  26. prize = []
  27.  
  28. file = open("13_input.txt", "r")
  29. line_count = 0
  30. for line in file:
  31.   line = line.replace("\n", "")
  32.   line_count += 1
  33.   if line_count % 4 == 1:
  34.     line = line.replace("Button A: X+", "")
  35.     line = line.replace(", Y+", " ")
  36.     parts = line.split(" ")
  37.     button_a.append([int(parts[0]), int(parts[1])])
  38.     continue
  39.   if line_count % 4 == 2:
  40.     line = line.replace("Button B: X+", "")
  41.     line = line.replace(", Y+", " ")
  42.     parts = line.split(" ")
  43.     button_b.append([int(parts[0]), int(parts[1])])
  44.     continue
  45.   if line_count % 4 == 3:
  46.     line = line.replace("Prize: X=", "")
  47.     line = line.replace(", Y=", " ")
  48.     parts = line.split(" ")
  49.     prize.append([int(parts[0]) + 10000000000000, int(parts[1]) + 10000000000000])
  50.     continue
  51.  
  52. total = 0
  53. for index in range(len(button_a)):
  54.   cost = get_cheapest_cost(button_a[index][0], button_a[index][1], button_b[index][0], button_b[index][1], prize[index][0], prize[index][1])
  55.   if cost >= 0:
  56.     total += cost
  57. print (total)
Add Comment
Please, Sign In to add comment