13.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. lines = []
  2. with open("13.input") as f:
  3. for line in f.readlines():
  4. lines.append(line.strip())
  5. busses = [int(x) for x in lines[1].split(",") if x != "x"]
  6. my_time = int(lines[0])
  7. times = [x - my_time % x for x in busses]
  8. my_bus = busses[times.index(min(times))]
  9. print("Answer 1: {}".format(my_bus * min(times)))
  10. busses = [(- i % int(x), int(x)) for (i, x) in enumerate(lines[1].split(",")) if x != "x"]
  11. def print_table(start, busses):
  12. end = start + busses[-1][0]
  13. for i in range(start, end):
  14. print("{}: ".format(i), end='')
  15. for (offset, interval) in busses:
  16. if i % interval == 0:
  17. print('D', end='')
  18. else:
  19. print('.', end='')
  20. print("")
  21. # Stolen from: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Pseudocode
  22. def extended_gcd(a, b):
  23. (old_r, r) = (a, b)
  24. (old_s, s) = (1, 0)
  25. (old_t, t) = (0, 1)
  26. while r != 0:
  27. quotient = int(old_r / r)
  28. (old_r, r) = (r, old_r - quotient * r)
  29. (old_s, s) = (s, old_s - quotient * s)
  30. (old_t, t) = (t, old_t - quotient * t)
  31. return (old_s, old_t)
  32. def combo(pair1, pair2):
  33. off1, int1 = pair1
  34. off2, int2 = pair2
  35. # This is fine since all IDs are primes
  36. new_int = int1 * int2
  37. # Find the smallest solution to
  38. # int1 * x + off1 = int2 * y + off2
  39. # int1 * x - int2 * y = 1 * (off2 - off1)
  40. x, y = extended_gcd(int1, -int2)
  41. # Correct signs
  42. if int1 * x - int2 * y != 1:
  43. x = -x
  44. y = -y
  45. x *= (off2 - off1)
  46. y *= (off2 - off1)
  47. assert int1 * x + off1 == int2 * y + off2
  48. return ((int1 * x + off1) % new_int, new_int)
  49. result_busses = list(busses)
  50. while len(result_busses) > 1:
  51. result_busses = [combo(result_busses[0], result_busses[1])] + result_busses[2:]
  52. print("Answer 2: {}".format(result_busses[0][0]))