day 13 part 1 and 2 cleaned up

This commit is contained in:
Tyrel Souza 2022-12-13 02:30:36 -05:00
parent 7996458cd8
commit 0e70268aa3

View File

@ -1,128 +1,106 @@
import matrix import matrix
import shared import shared
import itertools import itertools
import sys import functools
import os
def blockPrint():
sys.stdout = open(os.devnull, 'w')
# Restore
def enablePrint():
sys.stdout = sys.__stdout__
class BREAK(Exception):
pass
def part1(rows): def part1(rows):
groups = [list(v) for k, v in itertools.groupby(rows, key=lambda x: not x) if not k] groups = [list(v) for k, v in itertools.groupby(rows, key=lambda x: not x) if not k]
NEED = list(range(len(groups)))
indexes = [] indexes = []
for idx, (left, right) in enumerate(groups): for idx, (left, right) in enumerate(groups):
left = eval(left) left = eval(left)
right = eval(right) right = eval(right)
if idx not in NEED: # print(f"== Pair {idx+1} ==")
blockPrint() passes = check_group(left, right)
print(f"== Pair {idx+1} ==") if passes:
passes = check_group(left, right, idx, 0)
if idx not in NEED:
enablePrint()
if passes is True:
print(f"{idx+1} {matrix.colors.GREEN}{passes}{matrix.colors.ENDC}")
indexes.append(idx+1) indexes.append(idx+1)
elif passes is False: # if passes is True:
print(f"{idx+1} {matrix.colors.RED}{passes}{matrix.colors.ENDC}") # print(f"{idx+1} {matrix.colors.GREEN}{passes}{matrix.colors.ENDC}")
else: # elif passes is False:
print(f"{idx+1} {matrix.colors.BLUE}{passes}{matrix.colors.ENDC}") # print(f"{idx+1} {matrix.colors.RED}{passes}{matrix.colors.ENDC}")
print('-'*40) # else:
# print(f"{idx+1} {matrix.colors.BLUE}{passes}{matrix.colors.ENDC}")
print(sum(indexes)) print(sum(indexes))
spaces = lambda x: " " * x def check_group(left, right):
if isinstance(left, list) and isinstance(right, list):
# if both items are lists, loop over both
def check_group(left, right, group, depth=0): for idx in range(min(len(left), len(right))):
print(f"{spaces(depth)}- Compare {left} vs {right}, depth {depth}") check = check_group(left[idx], right[idx])
for idx, _ in enumerate(left): # bubble up the int comparisons, or list length comparisons
# print("starting for") if check is False:
try: return False
while True: elif check is True:
l = left[idx] return True
try: # is None, continue on! TALLY HO!
r = right[idx] else:
except IndexError: # If the left list runs out of items first, the inputs are in the right order.
print(" - Right side ran out of items, so inputs are not in the right order") if len(left) < len(right):
return False return True
# print("starting while") # If the right list runs out of items first, the inputs are not in the right order.
try: if len(left) > len(right):
if isinstance(l, int) and isinstance(r, int): return False
print(f"{spaces(depth)} - Compare {l} vs {r}") # If the lists are the same length and no comparison makes a decision about the order, continue checking the next part of the input.
if l == r: return None
#print(".......BREAK") elif isinstance(left, int) and isinstance(right, list):
raise BREAK() # If exactly one value is an integer, convert the integer to a list which contains
if l > r: # that integer as its only value, then retry the comparison.
print(f"{spaces(depth)} - Right is Smaller, so inputs IN WRONG ORDER, False") left = [left]
return False return check_group(left, right)
if l < r: elif isinstance(left, list) and isinstance(right, int):
print(f"{spaces(depth)} - Left is Smaller, so inputs IN RIGHT ORDER, True") # If exactly one value is an integer, convert the integer to a list which contains
return True # that integer as its only value, then retry the comparison.
except IndexError: right = [right]
print("INDEX ERROR RIGHT RAN OUT") return check_group(left, right)
return False
try:
if isinstance(l, list) and isinstance(r, list):
print(f"{spaces(depth)} - Both Lists {l} vs {r}")
check = check_group(l, r, group, depth+1)
if check is None:
print("check is none", depth)
continue
if check is False:
"checked list v list and false"
return False
break
except IndexError:
print("INDEX ERROR LEFT RAN OUT")
return True
#print(f"TEST: {repr(l)} vs {repr(r)}")
if isinstance(l, int) and isinstance(r, list):
left[idx] = [ l, ]
print("convert left to list")
continue
if isinstance(l, list) and isinstance(r, int):
right[idx] = [ r, ]
print(f"convert right {r} to list")
continue
except BREAK:
#print("......broke out of while")
continue
else: else:
print("Left side ran out of items so inputs are in the right order") # both ints now
return True # If the left integer is lower than the right integer, the inputs are in the right order.
if left < right:
return True
# If the left integer is higher than the right integer, the inputs are not in the right order.
elif left > right:
return False
#Otherwise, the inputs are the same integer; continue checking the next part of the input.
elif left == right:
return None
def part2(rows): def part2(rows):
print(rows) rows = [eval(r) for r in rows if r]
rows.append([[2]])
rows.append([[6]])
print("---")
wat = {True: 1,False: -1,}
def cmp(x, y):
return wat[check_group(x, y)]
s = sorted(rows, key=functools.cmp_to_key(cmp), reverse=True)
two = 0
six = 0
for idx, r in enumerate(s):
if r == [[2]]:
two = idx+1
if r == [[6]]:
six = idx+1
break
print(two * six)
def main(): def main():
rows = shared.load_rows(13) rows = shared.load_rows(13)
with shared.elapsed_timer() as elapsed: with shared.elapsed_timer() as elapsed:
part1(rows) part1(rows)
print(elapsed()) print("🕒", elapsed())
# with shared.elapsed_timer() as elapsed: with shared.elapsed_timer() as elapsed:
# part2(rows) part2(rows)
# print(elapsed()) print("🕒", elapsed())
if __name__ == "__main__": if __name__ == "__main__":