Created
December 18, 2021 05:50
-
-
Save sciyoshi/9d773bbccdab19465b3a7579ae3a829b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def convert(l, d=0): | |
for i, e in enumerate(l): | |
if isinstance(e, list): | |
yield from convert(e, d + 1) | |
else: | |
yield (e, d) | |
def reduce(l): | |
c = list(l) | |
for i, (e, d) in enumerate(l): | |
if d == 4 and l[i + 1][1] == 4: | |
if i > 0: | |
c[i - 1] = (c[i - 1][0] + e, c[i - 1][1]) | |
if i < len(l) - 2: | |
c[i + 2] = (c[i + 2][0] + l[i + 1][0], c[i + 2][1]) | |
c[i : i + 2] = [(0, d - 1)] | |
return c | |
for i, (e, d) in enumerate(l): | |
if e >= 10: | |
c[i : i + 1] = [(e // 2, d + 1), (math.ceil(e / 2), d + 1)] | |
return c | |
return c | |
def add(a, b): | |
result = [*[(i, j + 1) for i, j in a], *[(i, j + 1) for i, j in b]] | |
while True: | |
b = reduce(result) | |
if b == result: | |
return b | |
result = b | |
def unconvert(l): | |
result = [] | |
depth = 0 | |
q = result | |
for (e, d) in l: | |
q = result | |
for i in range(depth): | |
q = q[-1] | |
while depth < d: | |
q.append([]) | |
q = q[-1] | |
depth += 1 | |
q.append(e) | |
if len(q) >= 2: | |
depth -= 1 | |
return result | |
def mag(l): | |
if isinstance(l, int): | |
return l | |
if len(l) == 2: | |
return 3 * mag(l[0]) + 2 * mag(l[1]) | |
return sum((mag(e) if isinstance(e, list) else e) for e in l) | |
tot = convert(eval(LINES[0])) | |
for l in LINES[1:]: | |
l = convert(eval(l)) | |
tot = add(tot, l) | |
print( | |
mag( | |
[ | |
[ | |
[[tot[0][0], tot[1][0]], [tot[2][0], tot[3][0]]], | |
[[tot[4][0], tot[5][0]], [tot[6][0], tot[7][0]]], | |
], | |
[ | |
[[tot[8][0], tot[9][0]], [tot[10][0], tot[11][0]]], | |
[[tot[12][0], tot[13][0]], [tot[14][0], tot[15][0]]], | |
], | |
] | |
) | |
) | |
most = 0 | |
for a, b in itertools.combinations(LINES, 2): | |
res = add(convert(eval(a)), convert(eval(b))) | |
if all(x[1] == 3 for x in res): | |
best = mag( | |
[ | |
[ | |
[[res[0][0], res[1][0]], [res[2][0], res[3][0]]], | |
[[res[4][0], res[5][0]], [res[6][0], res[7][0]]], | |
], | |
[ | |
[[res[8][0], res[9][0]], [res[10][0], res[11][0]]], | |
[[res[12][0], res[13][0]], [res[14][0], res[15][0]]], | |
], | |
] | |
) | |
if best > most: | |
most = best | |
res = add(convert(eval(b)), convert(eval(a))) | |
if all(x[1] == 3 for x in res): | |
best = mag( | |
[ | |
[ | |
[[res[0][0], res[1][0]], [res[2][0], res[3][0]]], | |
[[res[4][0], res[5][0]], [res[6][0], res[7][0]]], | |
], | |
[ | |
[[res[8][0], res[9][0]], [res[10][0], res[11][0]]], | |
[[res[12][0], res[13][0]], [res[14][0], res[15][0]]], | |
], | |
] | |
) | |
if best > most: | |
most = best | |
print(most) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment