Created
December 18, 2024 11:15
-
-
Save uds5501/b96f0d9806bc351a353827481f2705dc to your computer and use it in GitHub Desktop.
AOC D13 P1,2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| tasks = [] | |
| def get_num(x): | |
| x = x.strip() | |
| return int(x[2:]) | |
| with open('input13.txt') as file: | |
| curr_lines = ['', '', ''] | |
| i = 0 | |
| for line in file: | |
| l = line.strip() | |
| if l == '': | |
| i = 0 | |
| continue | |
| else: | |
| curr_lines[i] = l.strip() | |
| i = i + 1 | |
| if i == 3: | |
| x_a, y_a = map(get_num, curr_lines[0].split(': ')[1].strip().split(', ')) | |
| x_b, y_b = map(get_num, curr_lines[1].split(': ')[1].strip().split(', ')) | |
| x_prize, y_prize = map(get_num, curr_lines[2].split(': ')[1].strip().split(', ')) | |
| tasks.append([(x_a, y_a), (x_b, y_b), (10000000000000+x_prize, 10000000000000+y_prize)]) | |
| i = 0 | |
| ans = 0 | |
| def get_greedy_ans(a, b, prize): | |
| x_a, y_a = a | |
| x_b, y_b = b | |
| x_prize, y_prize = prize | |
| z_prize = x_prize - y_prize | |
| z_a = x_a - y_a | |
| z_b = x_b - y_b | |
| k_prize = x_prize + y_prize | |
| k_a = x_a + y_a | |
| k_b = x_b + y_b | |
| a1 = np.array([[z_a, z_b], [k_a, k_b]]) | |
| b1 = np.array([z_prize, k_prize]) | |
| press = 10 ** 15 | |
| try: | |
| x = np.linalg.solve(a1, b1) | |
| s_a = x[0] | |
| s_b = x[1] | |
| floor_a = int(s_a) | |
| floor_b = int(s_b) | |
| ceil_a = int(np.ceil(s_a)) | |
| ceil_b = int(np.ceil(s_b)) | |
| for i in [floor_a, ceil_a]: | |
| for j in [floor_b, ceil_b]: | |
| if i * x_a + j * x_b == x_prize and i * y_a + j * y_b == y_prize: | |
| press = min(press, 3*i + j) | |
| except np.linalg.LinAlgError: | |
| return 0 | |
| if press == 10 ** 15: | |
| return 0 | |
| return press | |
| for t in tasks: | |
| ans += get_greedy_ans(t[0], t[1], t[2]) | |
| print(ans) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment