Skip to content

Instantly share code, notes, and snippets.

@sciyoshi
Created December 16, 2020 05:26
Show Gist options
  • Save sciyoshi/c104ac7e5e61e326505fc9482176684c to your computer and use it in GitHub Desktop.
Save sciyoshi/c104ac7e5e61e326505fc9482176684c to your computer and use it in GitHub Desktop.
tickets = []
rules = {}
valid_range = set()
total = 0
for l in LINES:
if l == "your ticket:" or l == "nearby tickets:":
continue
if ":" in l:
n, rule = l.split(": ")
a, b = rule.split(" or ")
x1, y1 = [int(z) for z in a.split("-")]
x2, y2 = [int(z) for z in b.split("-")]
rules[n] = set(range(x1, y1 + 1)) | set(range(x2, y2 + 1))
valid_range |= rules[n]
else:
ticket = ints(l)
valid = True
for field in ticket:
if field not in valid_range:
total += field
valid = False
if valid:
tickets.append(ticket)
print(total)
mapping = collections.defaultdict(list)
for field in rules:
for i in range(len(tickets[0])):
if all(ticket[i] in rules[field] for ticket in tickets):
mapping[field].append(i)
fixed = {}
while any(mapping.values()):
for field, remaining in mapping.items():
if len(remaining) == 1:
fixed[field] = remaining[0]
for other in mapping.values():
if fixed[field] in other:
other.remove(fixed[field])
break
result = 1
for field in fixed:
if field.startswith("departure"):
result *= tickets[0][fixed[field]]
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment