89 lines
1.8 KiB
Python
89 lines
1.8 KiB
Python
from lib import get_data, str_to_ints
|
|
|
|
data = get_data(__file__)
|
|
|
|
dps = []
|
|
ranges = []
|
|
lines = (l for l in data.splitlines())
|
|
|
|
index = 0
|
|
for line in lines:
|
|
if line.strip() == "":
|
|
break
|
|
if line.startswith("departure"):
|
|
dps.append(index)
|
|
a, b, c, d = str_to_ints(line.replace("-", " "))
|
|
# ranges.append(((a, b), (c, d)))
|
|
ranges.append((a, b, c, d))
|
|
index += 1
|
|
|
|
next(lines)
|
|
my_ticket = str_to_ints(next(lines))
|
|
next(lines)
|
|
next(lines)
|
|
|
|
error = 0
|
|
valid = []
|
|
fields = []
|
|
for line in lines:
|
|
# print(line)
|
|
has_error = False
|
|
field = []
|
|
for x in str_to_ints(line):
|
|
no_match = True
|
|
field.append(set())
|
|
for i, (a, b, c, d) in enumerate(ranges):
|
|
if a <= x <= b:
|
|
field[-1].add(i)
|
|
no_match = False
|
|
elif c <= x <= d:
|
|
field[-1].add(i)
|
|
no_match = False
|
|
if no_match:
|
|
has_error = True
|
|
error += x
|
|
if not has_error:
|
|
valid.append(line)
|
|
fields.append(field)
|
|
|
|
base = fields[0]
|
|
for field in fields[1:]:
|
|
for i in range(len(field)):
|
|
base[i] &= field[i]
|
|
print(error)
|
|
|
|
used = set()
|
|
done = False
|
|
base = [list(xs) for xs in base]
|
|
while not done:
|
|
done = True
|
|
single = None
|
|
for xs in base:
|
|
if len(xs) == 1 and xs[0] not in used:
|
|
single = xs[0]
|
|
used.add(single)
|
|
break
|
|
|
|
if single is not None:
|
|
for xs in base:
|
|
if len(xs) == 1:
|
|
continue
|
|
if single in xs:
|
|
xs.remove(single)
|
|
|
|
for xs in base:
|
|
if len(xs) != 1:
|
|
done = False
|
|
break
|
|
|
|
mapping = []
|
|
for xs in base:
|
|
(x,) = xs
|
|
mapping.append(x)
|
|
|
|
r = 1
|
|
for i, v in zip(mapping, my_ticket):
|
|
if i in dps:
|
|
r *= v
|
|
print(r)
|