16.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. from itertools import permutations
  2. lines = []
  3. with open("16.input") as f:
  4. for line in f.readlines():
  5. lines.append(line.strip())
  6. i = 0
  7. ranges = {}
  8. while lines[i] != "":
  9. name, rs = lines[i].split(":")
  10. rs = rs.strip().split(" or ")
  11. rs = [r.split("-") for r in rs]
  12. rs = [range(int(x), int(y) + 1) for [x, y] in rs]
  13. ranges[name] = rs
  14. i += 1
  15. i += 2
  16. my_ticket = [int(s) for s in lines[i].split(",")]
  17. i += 3
  18. invalid_sum = 0
  19. valid_tickets = []
  20. for line in lines[i:]:
  21. nums = [int(s) for s in line.split(",")]
  22. ticket_valid = True
  23. for num in nums:
  24. valid = False
  25. for pair in ranges.values():
  26. for r in pair:
  27. if num in r:
  28. valid = True
  29. if not valid:
  30. invalid_sum += num
  31. ticket_valid = False
  32. if ticket_valid:
  33. valid_tickets.append(nums)
  34. print("Answer 1:", invalid_sum)
  35. def check_field_valid(value, ranges):
  36. for range in ranges:
  37. if value in range:
  38. return True
  39. return False
  40. def find_valid_order(fields):
  41. eligible_fields = {}
  42. for (i, _) in enumerate(fields):
  43. eligible_fields[i] = []
  44. for field in fields:
  45. valid = True
  46. for ticket in valid_tickets:
  47. if not check_field_valid(ticket[i], ranges[field]):
  48. valid = False
  49. break
  50. if valid:
  51. eligible_fields[i].append(field)
  52. field_index = {}
  53. for (i, val) in sorted(eligible_fields.items(), key=lambda e: len(e[1])):
  54. val = list(val)
  55. for f in field_index.keys():
  56. try:
  57. val.remove(f)
  58. except ValueError:
  59. pass
  60. assert len(val) == 1
  61. field_index[val[0]] = i
  62. return field_index
  63. field_index = find_valid_order(list(ranges.keys()))
  64. result_product = 1
  65. for key in ranges.keys():
  66. if key.startswith("departure"):
  67. result_product *= my_ticket[field_index[key]]
  68. print("Answer 2:", result_product)