aoc2022/d13.py
2023-12-07 23:57:09 -05:00

116 lines
2.2 KiB
Python

import lib
EXAMPLE = """[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[[1],4]
[9]
[[8,7,6]]
[[4,4],4,4]
[[4,4],4,4,4]
[7,7,7,7]
[7,7,7]
[]
[3]
[[[]]]
[[]]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]
"""
def right_order(a, b):
if not a and not b:
return None
elif not a:
return True
elif not b:
return False
l, r = a[0], b[0]
if type(l) is int and type(r) is int:
if l < r:
return True
elif l > r:
return False
else:
return right_order(a[1:], b[1:])
if type(l) is int:
l = [l]
if type(r) is int:
r = [r]
o = right_order(l, r)
if o is not None:
return o
return right_order(a[1:], b[1:])
def solve(lines: list[str]):
res = 0
pairs = [[]]
for (i, line) in enumerate(lines):
if line.strip() == "":
pairs.append([])
else:
pairs[-1].append(eval(line))
for i, p in enumerate(pairs):
if not len(p) == 2:
continue
a, b = p[0], p[1]
o = right_order(a, b)
if o is True:
res += i + 1
if o is None:
raise Exception("NO DECISION")
# 37:00
return res
def solve2(lines: list[str]):
res = 0
packets = list(map(eval, lines))
p1 = [[2]]
packets.append(p1)
p2 = [[6]]
packets.append(p2)
resorted = True
while resorted:
resorted = False
for i in range(len(packets) - 1):
if not right_order(packets[i], packets[i + 1]):
packets[i], packets[i + 1] = packets[i + 1], packets[i]
resorted = True
p1i, p2i = 0, 0
for (i, p) in enumerate(packets):
if p == p1:
p1i = i + 1
elif p == p2:
p2i = i + 1
print(p1i, p2i)
# 44:00
return p1i * p2i
def main():
lines = lib.str_to_lines(EXAMPLE)
print("Example 1:", solve(lines))
lines = lib.str_to_lines(open("i13.txt").read())
print("Solution 1:", solve(lines))
lines = lib.str_to_lines_no_empty(EXAMPLE)
print("Example 2:", solve2(lines))
lines = lib.str_to_lines_no_empty(open("i13.txt").read())
print("Solution 2:", solve2(lines))
if __name__ == "__main__":
main()