Guest User

Untitled

a guest
Dec 12th, 2024
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. # Input: lines like
  2. #          Button A: X+#, Y+#
  3. #          Button B: X+#, Y+#
  4. #          Prize: X=#, Y=#
  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. #         (max 100 pushes per button)
  9. #         total cost across all sets of three lines
  10.  
  11. def get_cheapest_cost(ax, ay, bx, by, px, py):
  12.   cheapest_cost = -1
  13.   for na in range(101):
  14.     nb = int((px - na * ax) / bx)
  15.     if nb < 0 or nb > 100:
  16.       continue
  17.     if (na * ax) + (nb * bx) == px and (na * ay) + (nb * by) == py:
  18.       cost = 3 * na + nb
  19.       if cheapest_cost == -1 or cheapest_cost > cost:
  20.         cheapest_cost = cost
  21.   return cheapest_cost
  22.  
  23. button_a = []
  24. button_b = []
  25. prize = []
  26.  
  27. file = open("13_input.txt", "r")
  28. line_count = 0
  29. for line in file:
  30.   line = line.replace("\n", "")
  31.   line_count += 1
  32.   if line_count % 4 == 1:
  33.     line = line.replace("Button A: X+", "")
  34.     line = line.replace(", Y+", " ")
  35.     parts = line.split(" ")
  36.     button_a.append([int(parts[0]), int(parts[1])])
  37.     continue
  38.   if line_count % 4 == 2:
  39.     line = line.replace("Button B: X+", "")
  40.     line = line.replace(", Y+", " ")
  41.     parts = line.split(" ")
  42.     button_b.append([int(parts[0]), int(parts[1])])
  43.     continue
  44.   if line_count % 4 == 3:
  45.     line = line.replace("Prize: X=", "")
  46.     line = line.replace(", Y=", " ")
  47.     parts = line.split(" ")
  48.     prize.append([int(parts[0]), int(parts[1])])
  49.     continue
  50.  
  51. total = 0
  52. for index in range(len(button_a)):
  53.   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])
  54.   if cost >= 0:
  55.     total += cost
  56. print (total)
Advertisement
Add Comment
Please, Sign In to add comment