Advent of Code occurs at Dec 01 to 25 where each day, you will need to solve a puzzle. It is Festival and the problem statement is mostly related to Christmas.
Day 13 - Distress Signal
https://adventofcode.com/2022/day/13
Q1
import sys
from collections import defaultdict, deque
file1 = open(sys.argv[1], "r")
ans = 0
def check(a, b):
if a < b:
return "yes"
if a > b:
return "no"
def f(a, b):
ans = False
for p in zip(a, b):
if type(p[0]) == type(p[1]) == int:
ans = check(p[0], p[1])
elif type(p[0]) == type(p[1]) == type([]):
ans = f(p[0], p[1])
elif type(p[0]) == int and type(p[1]) == type([]):
ans = f([p[0]], p[1])
elif type(p[0]) == type([]) and type(p[1]) == int:
ans = f(p[0], [p[1]])
if ans:
break
if not ans:
if len(a) < len(b):
return "yes"
elif len(a) > len(b):
return "no"
return ans
cur = []
data = []
while True:
line = file1.readline()
if not line:
break
line = line.strip()
if not line:
data.append(cur[:])
cur = []
continue
cur.append(eval(line))
if len(cur) == 2:
data.append(cur[:])
for i, (a, b) in enumerate(data):
print(a, b)
if f(a, b) == "yes":
ans += i + 1
print(i + 1)
print(ans)
Q2
from functools import cmp_to_key
import sys
from collections import defaultdict, deque
file1 = open(sys.argv[1], "r")
ans = 0
def check(a, b):
if a < b:
return -1
if a > b:
return 1
return 0
def f(a, b):
ans = False
for p in zip(a, b):
if type(p[0]) == type(p[1]) == int:
ans = check(p[0], p[1])
elif type(p[0]) == type(p[1]) == type([]):
ans = f(p[0], p[1])
elif type(p[0]) == int and type(p[1]) == type([]):
ans = f([p[0]], p[1])
elif type(p[0]) == type([]) and type(p[1]) == int:
ans = f(p[0], [p[1]])
if ans:
break
if not ans:
if len(a) < len(b):
return -1
elif len(a) > len(b):
return 1
return ans
data = []
while True:
line = file1.readline()
if not line:
break
line = line.strip()
if line:
data.append(eval(line))
a=[[2]]
b=[[6]]
data.extend([a, b])
data.sort(key=cmp_to_key(f))
for x in data:
print(x)
print((data.index(a) + 1) * (data.index(b) + 1))
Trick: use the eval to simplify parsing inputs to mixed types of arrays/integers (multidimensional arrays).
Tenary Values
Q2 is sorting by cmp_to_key.