day12 not pretty at alllll
This commit is contained in:
parent
75088a6215
commit
491530d857
@ -1,9 +1,11 @@
|
||||
import shared
|
||||
from pprint import pprint as pp
|
||||
|
||||
|
||||
def run(SOMETHING):
|
||||
pp(SOMETHING)
|
||||
|
||||
|
||||
def main():
|
||||
spl = lambda y: [int(w) for w in y]
|
||||
rows = [row.rstrip().split() for row in shared.load(3)]
|
||||
|
@ -3,6 +3,7 @@ import imageio
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
|
||||
class Animate:
|
||||
def __init__(self, mx, day="CHANGEME"):
|
||||
self.mx = mx
|
||||
@ -24,13 +25,17 @@ class Animate:
|
||||
fig, ax = plt.subplots()
|
||||
ax.imshow(current, cmap=plt.cm.gray)
|
||||
ax.axis("off")
|
||||
_figpath = (f"gif-{self.day}/{self.f_count:05}.png")
|
||||
_figpath = f"gif-{self.day}/{self.f_count:05}.png"
|
||||
plt.savefig(_figpath)
|
||||
plt.close()
|
||||
|
||||
def animate(self, frameskip=1):
|
||||
with imageio.get_writer(f"gif-{self.day}/day{self.day}.gif", mode="I") as writer:
|
||||
names = [f"gif-{self.day}/{x:05}.png" for x in range(0,self.f_count, frameskip)]
|
||||
with imageio.get_writer(
|
||||
f"gif-{self.day}/day{self.day}.gif", mode="I"
|
||||
) as writer:
|
||||
names = [
|
||||
f"gif-{self.day}/{x:05}.png" for x in range(0, self.f_count, frameskip)
|
||||
]
|
||||
print(names)
|
||||
for filename in names:
|
||||
try:
|
||||
|
@ -6,7 +6,7 @@ def run(rows):
|
||||
elves = []
|
||||
current_elf = 0
|
||||
for row in rows:
|
||||
if row == '':
|
||||
if row == "":
|
||||
elves.append(current_elf)
|
||||
current_elf = 0
|
||||
continue
|
||||
@ -22,7 +22,6 @@ def run(rows):
|
||||
print(three)
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
with open(shared.get_fname(1), "r") as f:
|
||||
rows = [x.rstrip() for x in f.readlines()]
|
||||
|
@ -13,28 +13,15 @@ Moves = {
|
||||
"A": rock,
|
||||
"B": paper,
|
||||
"C": scissors,
|
||||
|
||||
"X": rock,
|
||||
"Y": paper,
|
||||
"Z": scissors,
|
||||
}
|
||||
|
||||
Scores = {
|
||||
rock: 1,
|
||||
paper: 2,
|
||||
scissors: 3
|
||||
}
|
||||
Scores = {rock: 1, paper: 2, scissors: 3}
|
||||
|
||||
LosesTo = {
|
||||
rock: paper,
|
||||
paper: scissors,
|
||||
scissors: rock
|
||||
}
|
||||
WinsTo = {
|
||||
paper: rock,
|
||||
scissors: paper,
|
||||
rock: scissors
|
||||
}
|
||||
LosesTo = {rock: paper, paper: scissors, scissors: rock}
|
||||
WinsTo = {paper: rock, scissors: paper, rock: scissors}
|
||||
|
||||
|
||||
def winner(opponent, me):
|
||||
@ -42,11 +29,16 @@ def winner(opponent, me):
|
||||
return 3 + Scores[me]
|
||||
|
||||
# wins
|
||||
if (opponent == rock and me == paper) or (opponent == paper and me == scissors) or (opponent == scissors and me == rock):
|
||||
if (
|
||||
(opponent == rock and me == paper)
|
||||
or (opponent == paper and me == scissors)
|
||||
or (opponent == scissors and me == rock)
|
||||
):
|
||||
return 6 + Scores[me]
|
||||
|
||||
return 0 + Scores[me]
|
||||
|
||||
|
||||
def which_move(opponent, me):
|
||||
if me == lose:
|
||||
return WinsTo[Moves[opponent]]
|
||||
@ -66,6 +58,7 @@ def run(moves):
|
||||
score += pts
|
||||
print(score)
|
||||
|
||||
|
||||
def main():
|
||||
rows = [row.rstrip().split() for row in shared.load(2)]
|
||||
run(rows)
|
||||
|
@ -15,15 +15,22 @@ Moves = {
|
||||
}
|
||||
|
||||
Scores = {
|
||||
R: 1, P: 2, S: 3, X: 0, Y: 3, Z: 6,
|
||||
R: 1,
|
||||
P: 2,
|
||||
S: 3,
|
||||
X: 0,
|
||||
Y: 3,
|
||||
Z: 6,
|
||||
}
|
||||
|
||||
|
||||
def run(moves):
|
||||
score = 0
|
||||
for o, a in moves:
|
||||
score += Scores[Moves[o][a]] + Scores[a]
|
||||
print(score)
|
||||
|
||||
|
||||
def main():
|
||||
rows = [row.rstrip().split() for row in shared.load(2)]
|
||||
run(rows)
|
||||
|
@ -11,6 +11,7 @@ def part1(rucksacks):
|
||||
total += string.ascii_letters.index(match) + 1
|
||||
print(total)
|
||||
|
||||
|
||||
def part2(rucksacks):
|
||||
total = 0
|
||||
for idx in range(0, len(rucksacks), 3):
|
||||
@ -28,5 +29,6 @@ def main():
|
||||
part1(rows)
|
||||
part2(rows)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
150
2022/python/day05.psg.py
Normal file
150
2022/python/day05.psg.py
Normal file
@ -0,0 +1,150 @@
|
||||
from pprint import pprint as pp
|
||||
import PySimpleGUI as sg
|
||||
from shared import load_rows
|
||||
from scanf import scanf
|
||||
from string import ascii_letters
|
||||
import re
|
||||
|
||||
WATCHERS = {}
|
||||
OUTPUT = []
|
||||
|
||||
|
||||
def load_crates(x):
|
||||
done_crates = False
|
||||
crates = []
|
||||
instructions = []
|
||||
for row in x:
|
||||
if done_crates:
|
||||
instructions.append(row)
|
||||
else:
|
||||
if row == "":
|
||||
done_crates = True
|
||||
else:
|
||||
crates.append(row)
|
||||
crates.pop()
|
||||
return crates, instructions
|
||||
|
||||
|
||||
def to_lists(crates):
|
||||
parsed = []
|
||||
reg = re.compile(r"[\([{})\]]")
|
||||
for row in crates:
|
||||
parsed.append([x for x in reg.sub(" ", row)])
|
||||
parsed = list(zip(*parsed[::-1]))
|
||||
parsed = list(zip(*parsed[::-1]))
|
||||
parsed = list(zip(*parsed[::-1]))
|
||||
cleaned1 = [[x for x in y if x.strip()] for y in parsed if y]
|
||||
cleaned2 = [x for x in cleaned1 if x != []][::-1]
|
||||
return cleaned2
|
||||
|
||||
|
||||
def parse_instructions(crates, instructions):
|
||||
for instruction in instructions:
|
||||
count, _from, _to = scanf("move %d from %d to %d", instruction)
|
||||
update_watchers("count", count)
|
||||
update_output(" ".join(map(str, (count, _from, _to))))
|
||||
_from -= 1 # 1 based yo
|
||||
_to -= 1
|
||||
for x in range(count):
|
||||
value = crates[_from].pop(0)
|
||||
crates[_to].insert(0, value)
|
||||
return crates
|
||||
|
||||
|
||||
def parse_instructions_pt2(crates, instructions):
|
||||
for instruction in instructions:
|
||||
count, _from, _to = scanf("move %d from %d to %d", instruction)
|
||||
_from -= 1 # 1 based yo
|
||||
_to -= 1
|
||||
moving = crates[_from][:count]
|
||||
update_output(" ".join(map(str, (instruction, moving))))
|
||||
for x in range(count):
|
||||
crates[_from].pop(0)
|
||||
for x in reversed(moving):
|
||||
crates[_to].insert(0, x)
|
||||
|
||||
return crates
|
||||
|
||||
|
||||
def part1(x):
|
||||
crates, instructions = load_crates(x)
|
||||
crates = to_lists(crates)
|
||||
crates = parse_instructions(crates, instructions)
|
||||
update_output("".join([c[0] for c in crates]))
|
||||
|
||||
|
||||
def part2(x):
|
||||
crates, instructions = load_crates(x)
|
||||
crates = parse_instructions_pt2(crates, instructions)
|
||||
update_output("".join([c[0] for c in crates]))
|
||||
|
||||
|
||||
def main():
|
||||
rows = load_rows(5)
|
||||
sg_window(rows)
|
||||
|
||||
|
||||
sg.Window("Day5")
|
||||
sg.theme("DarkAmber")
|
||||
watch_column = [
|
||||
[sg.Text("Watch Column")],
|
||||
[sg.Text("------------")],
|
||||
[sg.Text("", key="-WATCH-")],
|
||||
]
|
||||
output_column = [
|
||||
[sg.Text("Output Column")],
|
||||
[sg.Text("------------")],
|
||||
[sg.Text("", key="-OUTPUT-")],
|
||||
]
|
||||
|
||||
layout = [
|
||||
[sg.Button("Part1"), sg.Button("Part2"), sg.Button("X")],
|
||||
[
|
||||
sg.Column(watch_column),
|
||||
sg.VSeperator(),
|
||||
sg.Column(output_column),
|
||||
],
|
||||
]
|
||||
|
||||
window = sg.Window("App", layout)
|
||||
|
||||
|
||||
def update_output(new):
|
||||
new = new.split("\n")
|
||||
global OUTPUT
|
||||
OUTPUT.extend(new)
|
||||
if len(OUTPUT) > 40:
|
||||
OUTPUT = OUTPUT[len(new) :]
|
||||
window["-OUTPUT-"].update("\n".join(OUTPUT))
|
||||
|
||||
|
||||
def watcher_to_string():
|
||||
s = ""
|
||||
for k, v in WATCHERS.items():
|
||||
s += f"{k}:{v}\n"
|
||||
return s
|
||||
|
||||
|
||||
def update_watchers(k, v):
|
||||
WATCHERS[k] = v
|
||||
window["-WATCH-"].update(watcher_to_string())
|
||||
|
||||
|
||||
def sg_window(rows):
|
||||
while True:
|
||||
event, values = window.Read()
|
||||
if event == "X" or event == sg.WIN_CLOSED:
|
||||
break
|
||||
if event == "Part1":
|
||||
part1(rows)
|
||||
if event == "Part2":
|
||||
part2(rows)
|
||||
|
||||
window.Close()
|
||||
|
||||
# part1(rows)
|
||||
# part2(rows)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -13,13 +13,14 @@ def load_crates(x):
|
||||
if done_crates:
|
||||
instructions.append(row)
|
||||
else:
|
||||
if row == '':
|
||||
if row == "":
|
||||
done_crates = True
|
||||
else:
|
||||
crates.append(row)
|
||||
crates.pop()
|
||||
return crates, instructions
|
||||
|
||||
|
||||
def to_lists(crates):
|
||||
parsed = []
|
||||
reg = re.compile(r"[\([{})\]]")
|
||||
@ -32,6 +33,7 @@ def to_lists(crates):
|
||||
cleaned2 = [x for x in cleaned1 if x != []][::-1]
|
||||
return cleaned2
|
||||
|
||||
|
||||
def parse_instructions(crates, instructions):
|
||||
for instruction in instructions:
|
||||
count, _from, _to = scanf("move %d from %d to %d", instruction)
|
||||
@ -43,6 +45,7 @@ def parse_instructions(crates, instructions):
|
||||
crates[_to].insert(0, value)
|
||||
return crates
|
||||
|
||||
|
||||
def parse_instructions_pt2(crates, instructions):
|
||||
for instruction in instructions:
|
||||
count, _from, _to = scanf("move %d from %d to %d", instruction)
|
||||
|
@ -1,14 +1,17 @@
|
||||
from shared import load_rows
|
||||
|
||||
|
||||
def part1(row, group_size=4):
|
||||
for x in range(len(row)):
|
||||
if (len(set(row[x:x+group_size])) == group_size):
|
||||
if len(set(row[x : x + group_size])) == group_size:
|
||||
print(x + group_size)
|
||||
break
|
||||
|
||||
|
||||
def part2(row):
|
||||
part1(row, 14)
|
||||
|
||||
|
||||
def main():
|
||||
rows = load_rows(6)
|
||||
for row in rows:
|
||||
|
@ -10,22 +10,26 @@ import operator
|
||||
PWD = []
|
||||
FS = {"/": {".": {"size": 0, "files": []}}}
|
||||
|
||||
|
||||
def get_keys(input_dict):
|
||||
for key, value in input_dict.items():
|
||||
if isinstance(value, dict):
|
||||
for subkey in get_keys(value):
|
||||
yield key + ',' + subkey
|
||||
yield key + "," + subkey
|
||||
else:
|
||||
if key in ("files"):
|
||||
continue
|
||||
yield f"{value}"
|
||||
|
||||
|
||||
def getFromDict(mapList):
|
||||
return reduce(operator.getitem, mapList, FS)
|
||||
|
||||
|
||||
def setInDict(mapList, value):
|
||||
getFromDict(mapList[:-1])[mapList[-1]] = value
|
||||
|
||||
|
||||
def addInDict(mapList, filename, value):
|
||||
try:
|
||||
v = getFromDict(mapList[:-1])[mapList[-1]]
|
||||
@ -44,12 +48,11 @@ def addInDict(mapList, filename, value):
|
||||
getFromDict(mapList[:-1])[mapList[-1]] = v
|
||||
|
||||
|
||||
|
||||
|
||||
def part1(rows):
|
||||
build_fs(rows)
|
||||
# calculate_directories()
|
||||
|
||||
|
||||
def calculate_directories():
|
||||
keys = list(get_keys(FS))
|
||||
new_FS = {}
|
||||
@ -69,7 +72,7 @@ def calculate_directories():
|
||||
print(new_FS.keys())
|
||||
print("keys^")
|
||||
for pwd, directory in new_FS.items():
|
||||
parent = directory['parent']
|
||||
parent = directory["parent"]
|
||||
if parent:
|
||||
print(parent)
|
||||
# print(f"{pwd}:{parent} Adding {directory['size']} to fullsize {new_FS[parent]['full_size']}")
|
||||
@ -78,7 +81,7 @@ def calculate_directories():
|
||||
|
||||
sizes = []
|
||||
for k, v in new_FS.items():
|
||||
sizes.append(v['size'])
|
||||
sizes.append(v["size"])
|
||||
total = 0
|
||||
|
||||
for size in sizes:
|
||||
@ -88,6 +91,7 @@ def calculate_directories():
|
||||
|
||||
print("=", total)
|
||||
|
||||
|
||||
def build_fs(rows):
|
||||
LS_ING = False
|
||||
for row in rows:
|
||||
@ -113,6 +117,7 @@ def build_fs(rows):
|
||||
add_file(parts[1], int(parts[0]))
|
||||
jp(FS)
|
||||
|
||||
|
||||
def jp(d):
|
||||
output = json.dumps(FS, indent=4)
|
||||
output2 = re.sub(r'": \[\s+', '": [', output)
|
||||
@ -125,6 +130,7 @@ def add_directory(dirname):
|
||||
temp_new_path = PWD + [dirname]
|
||||
setInDict(temp_new_path, {".": {"size": 0, "files": []}})
|
||||
|
||||
|
||||
def add_file(filename, size):
|
||||
# print(".", PWD, filename, size)
|
||||
mapList = PWD + ["."]
|
||||
@ -143,6 +149,7 @@ def add_file(filename, size):
|
||||
def part2(row):
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
rows = load_rows(7)
|
||||
part1(rows)
|
||||
|
@ -3,7 +3,6 @@ import shared
|
||||
import matrix
|
||||
|
||||
|
||||
|
||||
def part1(mx):
|
||||
SIZE = len(mx)
|
||||
MAX_IDX = SIZE - 1
|
||||
@ -105,7 +104,7 @@ def part2(mx):
|
||||
# Calculate score
|
||||
score = 1 # identity yoooo
|
||||
cell = data[row][col]
|
||||
val = cell['value']
|
||||
val = cell["value"]
|
||||
# Get the score of visible trees in each direction
|
||||
for direction in ("u", "l", "d", "r"):
|
||||
in_line = cell[direction]
|
||||
@ -126,6 +125,7 @@ def part2(mx):
|
||||
high_score = score
|
||||
print(high_score)
|
||||
|
||||
|
||||
def part2_with_fixes(mx):
|
||||
SIZE = len(mx)
|
||||
MAX_IDX = SIZE - 1
|
||||
@ -149,7 +149,7 @@ def part2_with_fixes(mx):
|
||||
|
||||
# Calculate score
|
||||
score = 1 # identity yoooo
|
||||
val = data[row][col]['value']
|
||||
val = data[row][col]["value"]
|
||||
# Get the score of visible trees in each direction
|
||||
for direction in ("u", "l", "d", "r"):
|
||||
in_line = data[row][col][direction]
|
||||
@ -170,6 +170,7 @@ def part2_with_fixes(mx):
|
||||
high_score = score
|
||||
print(high_score)
|
||||
|
||||
|
||||
def main():
|
||||
mx = matrix.load_matrix_file(shared.get_fname(8))
|
||||
with shared.elapsed_timer() as elapsed:
|
||||
@ -183,6 +184,5 @@ def main():
|
||||
print(elapsed())
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
@ -14,17 +14,17 @@ T = [HALF,HALF]
|
||||
|
||||
# returns (x,y) - so remember to take dx,dy lower
|
||||
DIRS = {
|
||||
'U': matrix.M_U, # (0, -1)
|
||||
'D': matrix.M_D,
|
||||
'L': matrix.M_L,
|
||||
'R': matrix.M_R,
|
||||
|
||||
'UR': matrix.M_UR, # (+1, -1)
|
||||
'DR': matrix.M_DR,
|
||||
'UL': matrix.M_UL,
|
||||
'DL': matrix.M_DL,
|
||||
"U": matrix.M_U, # (0, -1)
|
||||
"D": matrix.M_D,
|
||||
"L": matrix.M_L,
|
||||
"R": matrix.M_R,
|
||||
"UR": matrix.M_UR, # (+1, -1)
|
||||
"DR": matrix.M_DR,
|
||||
"UL": matrix.M_UL,
|
||||
"DL": matrix.M_DL,
|
||||
}
|
||||
|
||||
|
||||
def part1(steps):
|
||||
field = matrix.matrix_of_size(MATRIX_SIZE, MATRIX_SIZE)
|
||||
anim = Animate(field, day="09")
|
||||
@ -66,7 +66,6 @@ def part1(steps):
|
||||
elif bX > kX:
|
||||
tX = 1
|
||||
|
||||
|
||||
# if Head Y is less than Tail Y, move Tail Y 1 up
|
||||
if HY < kY:
|
||||
tY = -1
|
||||
@ -86,7 +85,9 @@ def part1(steps):
|
||||
def part2(steps):
|
||||
field = matrix.matrix_of_size(MATRIX_SIZE, MATRIX_SIZE)
|
||||
anim = Animate(field, day="09")
|
||||
S = [[HALF,HALF],] # HEAD ONLY
|
||||
S = [
|
||||
[HALF, HALF],
|
||||
] # HEAD ONLY
|
||||
_cur_frame = 0
|
||||
for x in range(9):
|
||||
S.append([HALF, HALF])
|
||||
@ -151,7 +152,6 @@ def part2(steps):
|
||||
anim.animate()
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
rows = [x.split(" ") for x in shared.load_rows(9)]
|
||||
# part1(rows)
|
||||
|
@ -7,6 +7,7 @@ cycles = {
|
||||
"addx": 2,
|
||||
}
|
||||
|
||||
|
||||
def part1(x):
|
||||
X = 1
|
||||
cycle_count = 0
|
||||
@ -30,8 +31,6 @@ def part1(x):
|
||||
print(sum(signal_strength))
|
||||
|
||||
|
||||
|
||||
|
||||
def part2(x):
|
||||
def cycle_to_xy(cycle):
|
||||
x = cycle % 40
|
||||
@ -64,6 +63,7 @@ def part2(x):
|
||||
anim.add_frame(screen)
|
||||
print("wrote gif-10/day10.gif")
|
||||
|
||||
|
||||
def main():
|
||||
rows = [row for row in shared.load(10)]
|
||||
part1(rows)
|
||||
|
@ -30,9 +30,9 @@ def load_monkeys(lines):
|
||||
by = int(line.split(" ")[-1])
|
||||
except ValueError:
|
||||
by = None # know None means by self
|
||||
if '*' in op:
|
||||
if "*" in op:
|
||||
operand = operator.mul
|
||||
elif '+' in op:
|
||||
elif "+" in op:
|
||||
operand = operator.add
|
||||
elif line.lstrip().startswith("Test"):
|
||||
div = int(line.split(" ")[-1])
|
||||
@ -41,19 +41,14 @@ def load_monkeys(lines):
|
||||
elif line.lstrip().startswith("If false"):
|
||||
false = int(line.split(" ")[-1])
|
||||
monkey = Monkey(
|
||||
number=count,
|
||||
items=items,
|
||||
op=operand,
|
||||
by=by,
|
||||
div=div,
|
||||
t=true,
|
||||
f=false
|
||||
number=count, items=items, op=operand, by=by, div=div, t=true, f=false
|
||||
)
|
||||
monkeys.append(monkey)
|
||||
count += 1
|
||||
lcm = math.lcm(*[m.div for m in monkeys])
|
||||
return monkeys, lcm
|
||||
|
||||
|
||||
def part1(lines):
|
||||
monkeys, _ = load_monkeys(lines)
|
||||
|
||||
|
116
2022/python/day12.py
Normal file
116
2022/python/day12.py
Normal file
@ -0,0 +1,116 @@
|
||||
import shared
|
||||
import matrix
|
||||
from dijkstar import Graph, find_path, algorithm
|
||||
|
||||
|
||||
#def dj_walk(mx, start, end):
|
||||
# def next_cost(c, val):
|
||||
# if val > c+1:
|
||||
# return 9999
|
||||
# else:
|
||||
# return val
|
||||
#
|
||||
# start = start[1], start[0]
|
||||
# end = end[1], end[0]
|
||||
#
|
||||
# # Dijkstra from RedBlobGames
|
||||
# frontier = PriorityQueue()
|
||||
# frontier.put(start, 0)
|
||||
# came_from = dict()
|
||||
# cost_so_far = dict()
|
||||
# came_from[start] = None
|
||||
# cost_so_far[start] = 0
|
||||
# last = None
|
||||
# while not frontier.empty():
|
||||
# x, y = frontier.get()
|
||||
# cur = (x, y)
|
||||
# if cur == end:
|
||||
# break
|
||||
# for _n in matrix.get_neighbors(mx, x=x, y=y, _dict=True):
|
||||
# nxt = (_n["x"], _n["y"])
|
||||
# v = _n["value"]
|
||||
#
|
||||
# new_cost = next_cost(cost_so_far[cur], v)
|
||||
# if nxt not in cost_so_far or new_cost < cost_so_far[nxt]:
|
||||
# cost_so_far[nxt] = new_cost
|
||||
# priority = new_cost
|
||||
# frontier.put(nxt, priority)
|
||||
# came_from[nxt] = cur
|
||||
# last = cur
|
||||
# print(len(cost_so_far))
|
||||
|
||||
criteria = lambda _cur, _neighbor: _neighbor - _cur <= 1
|
||||
def build_graph(mx):
|
||||
graph = Graph()
|
||||
for y, row in enumerate(mx):
|
||||
for x, _ in enumerate(row):
|
||||
neighbors = matrix.valid_neighbors(mx, x=x, y=y, criteria=criteria)
|
||||
for neighbor in neighbors:
|
||||
graph.add_edge((y, x), (neighbor['y'],neighbor['x']), 1)
|
||||
return graph
|
||||
|
||||
|
||||
|
||||
#SEEN = []
|
||||
#def walk(mx, y, x, seen=[]):
|
||||
# print(len(seen))
|
||||
# valid_next = matrix.valid_neighbors(mx, y, x, criteria=criteria)
|
||||
# print(valid_next)
|
||||
# matrix.highlight( mx, red=seen, green=[ *valid_next, ], blue=[ END, ],)
|
||||
# for next_yx in valid_next:
|
||||
# if next_yx not in seen:
|
||||
# seen.append(next_yx)
|
||||
# _y, _x = next_yx
|
||||
# walk(mx, _y, _x, seen)
|
||||
# else:
|
||||
# seen.append(next_yx)
|
||||
|
||||
def elev(yx):
|
||||
y,x = yx
|
||||
return mx[y][x]
|
||||
|
||||
def part1(mx):
|
||||
start = matrix.find_in_matrix(mx, "S")
|
||||
end = matrix.find_in_matrix(mx, "E")
|
||||
mx[start[0]][start[1]] = "a"
|
||||
mx[end[0]][end[1]] = "z"
|
||||
matrix.apply_to_all(mx, lambda x: ord(x) - ord('a'))
|
||||
|
||||
#walk(mx, cur[0],cur[0], seen=[(cur[0],cur[1])])
|
||||
#dj_walk(mx, cur, END)
|
||||
graph = build_graph(mx)
|
||||
path = find_path(graph, start, end)
|
||||
print(len(path.nodes))
|
||||
|
||||
|
||||
def part2(mx):
|
||||
end = matrix.find_in_matrix(mx, "E")
|
||||
s = matrix.find_in_matrix(mx, "S")
|
||||
mx[s[0]][s[1]] = "a"
|
||||
mx[end[0]][end[1]] = "z"
|
||||
|
||||
starts = matrix.find_in_matrix(mx, 'a', one=False)
|
||||
matrix.apply_to_all(mx, lambda x: ord(x) - ord('a'))
|
||||
graph = build_graph(mx)
|
||||
|
||||
n_counts = []
|
||||
for start in starts:
|
||||
#walk(mx, cur[0],cur[0], seen=[(cur[0],cur[1])])
|
||||
#dj_walk(mx, cur, END)
|
||||
try:
|
||||
path = find_path(graph, start, end)
|
||||
n_counts.append(len(path.nodes)-1)
|
||||
except algorithm.NoPathError:
|
||||
pass
|
||||
print(n_counts)
|
||||
print(min(n_counts))
|
||||
|
||||
|
||||
def main():
|
||||
mx = matrix.load_matrix_file(shared.get_fname(12), matrix.split_word_to_chr_list)
|
||||
#part1(mx)
|
||||
part2(mx)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -1,10 +1,28 @@
|
||||
from copy import deepcopy
|
||||
from collections import defaultdict
|
||||
|
||||
from typing import List, Dict, Tuple
|
||||
|
||||
split_word_to_chr_list = lambda y: [w for w in y]
|
||||
split_word_to_int_list = lambda y: [int(w) for w in y]
|
||||
split_line_to_int_list = lambda y: [int(w) for w in y.split(" ") if w]
|
||||
|
||||
|
||||
class colors:
|
||||
# HEADER = '\033[95m'
|
||||
BLUE = "\033[94m"
|
||||
GREEN = "\033[92m"
|
||||
YELLOW = "\033[93m"
|
||||
RED = "\033[91m"
|
||||
ENDC = "\033[0m"
|
||||
|
||||
|
||||
def apply_to_all(mx, func):
|
||||
for row_num, row in enumerate(mx):
|
||||
for col_num, val in enumerate(row):
|
||||
mx[row_num][col_num] = func(val)
|
||||
|
||||
|
||||
def rotate(m, right=True): # -90
|
||||
"""
|
||||
Takes a matrix, and rotates all of the values 90 degrees to the left
|
||||
@ -28,13 +46,26 @@ def load_matrix_file(name, func=None):
|
||||
return [split_word_to_int_list(x) for x in my_file]
|
||||
|
||||
|
||||
def find_in_matrix(mx, what, one=True):
|
||||
coords = []
|
||||
for row_num, row in enumerate(mx):
|
||||
for col_num, val in enumerate(row):
|
||||
if val == what:
|
||||
coord = (row_num, col_num)
|
||||
if one is True:
|
||||
return coord
|
||||
else:
|
||||
coords.append(coord)
|
||||
return coords
|
||||
|
||||
|
||||
def get_neighbors(matrix, x, y, _dict=False):
|
||||
neighbors = []
|
||||
# left
|
||||
try:
|
||||
if x - 1 >= 0:
|
||||
if _dict:
|
||||
neighbors.append({'x':x - 1,'y':y,'value':matrix[y][x - 1]})
|
||||
neighbors.append({"x": x - 1, "y": y, "value": matrix[y][x - 1]})
|
||||
else:
|
||||
neighbors.append([(x - 1, y), matrix[y][x - 1]])
|
||||
except IndexError:
|
||||
@ -42,7 +73,7 @@ def get_neighbors(matrix, x, y, _dict=False):
|
||||
# right
|
||||
try:
|
||||
if _dict:
|
||||
neighbors.append({'x':x + 1,'y':y,'value':matrix[y][x + 1]})
|
||||
neighbors.append({"x": x + 1, "y": y, "value": matrix[y][x + 1]})
|
||||
else:
|
||||
neighbors.append([(x + 1, y), matrix[y][x + 1]])
|
||||
except IndexError:
|
||||
@ -52,7 +83,7 @@ def get_neighbors(matrix, x, y, _dict=False):
|
||||
try:
|
||||
if y - 1 >= 0:
|
||||
if _dict:
|
||||
neighbors.append({'x':x,'y':y-1,'value':matrix[y-1][x]})
|
||||
neighbors.append({"x": x, "y": y - 1, "value": matrix[y - 1][x]})
|
||||
else:
|
||||
neighbors.append([(x, y - 1), matrix[y - 1][x]])
|
||||
except IndexError:
|
||||
@ -61,7 +92,7 @@ def get_neighbors(matrix, x, y, _dict=False):
|
||||
# down
|
||||
try:
|
||||
if _dict:
|
||||
neighbors.append({'x':x,'y':y+1,'value':matrix[y+1][x]})
|
||||
neighbors.append({"x": x, "y": y + 1, "value": matrix[y + 1][x]})
|
||||
else:
|
||||
neighbors.append([(x, y + 1), matrix[y + 1][x]])
|
||||
except IndexError:
|
||||
@ -69,6 +100,19 @@ def get_neighbors(matrix, x, y, _dict=False):
|
||||
|
||||
return neighbors
|
||||
|
||||
|
||||
def valid_neighbors(matrix, x, y, criteria=None):
|
||||
if criteria is None:
|
||||
raise Exception("Please pass in a lambda for criteria")
|
||||
cur = matrix[y][x]
|
||||
neighbors = get_neighbors(matrix, x, y, _dict=True)
|
||||
valid = []
|
||||
for neighbor in neighbors:
|
||||
if criteria(cur, neighbor['value']):
|
||||
valid.append(neighbor)
|
||||
return valid
|
||||
|
||||
|
||||
def sum_matrix(mtx):
|
||||
total = 0
|
||||
for row in mtx:
|
||||
@ -80,27 +124,20 @@ M_UL, M_U, M_UR = (-1, -1), (0, -1), (1, -1)
|
||||
M_L, M_R = (-1, 0), (1, 0)
|
||||
M_DL, M_D, M_DR = (-1, 1), (0, 1), (1, 1)
|
||||
|
||||
|
||||
def get_neighbor_coords(matrix, c, r, diagonals=True):
|
||||
height = len(matrix)
|
||||
width = len(matrix[0])
|
||||
if diagonals:
|
||||
coords = (
|
||||
M_UL, M_U, M_UR,
|
||||
M_L, M_R,
|
||||
M_DL, M_D, M_DR
|
||||
)
|
||||
coords = (M_UL, M_U, M_UR, M_L, M_R, M_DL, M_D, M_DR)
|
||||
else:
|
||||
coords = (
|
||||
M_U,
|
||||
M_L,M_R,
|
||||
M_D
|
||||
)
|
||||
coords = (M_U, M_L, M_R, M_D)
|
||||
neighbors = []
|
||||
|
||||
for _c, _r in coords:
|
||||
try:
|
||||
value = matrix[r + _r][c + _c] # Try to get a value error
|
||||
if (r+_r>=0 and c+_c >= 0):
|
||||
if r + _r >= 0 and c + _c >= 0:
|
||||
neighbors.append(
|
||||
[{"c": c + _c, "r": r + _r}, value]
|
||||
) # woo, no error, this coord is valid
|
||||
@ -108,6 +145,7 @@ def get_neighbor_coords(matrix, c, r, diagonals=True):
|
||||
pass # okay we out of bounds boizzzz
|
||||
return neighbors
|
||||
|
||||
|
||||
def line_of_sight_coords(matrix, row, col) -> Dict[str, List[Tuple[int, int]]]:
|
||||
"""
|
||||
Takes a matrix, a row, and a column
|
||||
@ -130,12 +168,13 @@ def line_of_sight_coords(matrix, row,col) -> Dict[str,List[Tuple[int,int]]]:
|
||||
down = [(row, c) for c in down_ids]
|
||||
|
||||
return {
|
||||
'U':up,
|
||||
'L':left,
|
||||
'D':down,
|
||||
'R':right,
|
||||
"U": up,
|
||||
"L": left,
|
||||
"D": down,
|
||||
"R": right,
|
||||
}
|
||||
|
||||
|
||||
def line_of_sight(mx, row, col):
|
||||
"""
|
||||
renders a line of sight coord calculation, into the values
|
||||
@ -148,12 +187,12 @@ def line_of_sight(mx, row, col):
|
||||
return los
|
||||
|
||||
|
||||
|
||||
def get_size(matrix):
|
||||
height = len(matrix)
|
||||
width = len(matrix[0])
|
||||
return height, width
|
||||
|
||||
|
||||
def row_col_from_int(matrix, x):
|
||||
h, w = get_size(matrix)
|
||||
col = x % w
|
||||
@ -164,6 +203,7 @@ def row_col_from_int(matrix, x):
|
||||
def matrix_of_size(width, height, default=0):
|
||||
return [[default] * width for x in range(height)]
|
||||
|
||||
|
||||
def set_matrix_dict(m):
|
||||
for x in range(len(m)):
|
||||
for y in range(len(m[x])):
|
||||
@ -195,6 +235,7 @@ def pmx(*matrices, pad=True, space=True):
|
||||
f = lambda x: f"{int(x)or '.'} "
|
||||
print("".join([f(x) for x in c]))
|
||||
|
||||
|
||||
def ppmx(*matrices, pad=True, space=True):
|
||||
"""
|
||||
print a matrix of anything, Falsy values turns to `.` for clarity
|
||||
@ -218,3 +259,23 @@ def ppmx(*matrices, pad=True, space=True):
|
||||
if space:
|
||||
f = lambda x: f"{x or '.'} "
|
||||
print("".join([f(x) for x in c]))
|
||||
|
||||
|
||||
def highlight(matrix, red=[], green=[], blue=[]):
|
||||
"""
|
||||
print a matrix of anything, Falsy values turns to `.` for clarity
|
||||
"""
|
||||
mx = deepcopy(matrix)
|
||||
for (y, x) in red:
|
||||
try:
|
||||
new = f"{colors.RED}{mx[y][x]}{colors.ENDC}"
|
||||
mx[y][x] = new
|
||||
except IndexError:
|
||||
breakpoint()
|
||||
for (y, x) in green:
|
||||
new = f"{colors.GREEN}{mx[y][x]}{colors.ENDC}"
|
||||
mx[y][x] = new
|
||||
for (y, x) in blue:
|
||||
new = f"{colors.BLUE}{mx[y][x]}{colors.ENDC}"
|
||||
mx[y][x] = new
|
||||
ppmx(mx, pad=False, space=False)
|
||||
|
@ -4,13 +4,16 @@ from pathlib import Path
|
||||
|
||||
spl = lambda y: [int(w) for w in y]
|
||||
|
||||
|
||||
def load_rows(day):
|
||||
return [row for row in load(day)]
|
||||
|
||||
|
||||
def load(day):
|
||||
path = Path(get_fname(day))
|
||||
return path.read_text().rstrip().split("\n")
|
||||
|
||||
|
||||
def get_fname(day: int) -> str:
|
||||
import sys
|
||||
|
||||
@ -27,6 +30,7 @@ def load_char_matrix(f):
|
||||
my_file.append(line.rstrip())
|
||||
return [list(x) for x in my_file]
|
||||
|
||||
|
||||
def load_file_char_matrix(name):
|
||||
with open(name, "r") as f:
|
||||
return load_char_matrix(f)
|
||||
@ -38,21 +42,27 @@ def load_int_matrix(f):
|
||||
my_file.append(line.rstrip())
|
||||
return [list(map(int, x)) for x in my_file]
|
||||
|
||||
|
||||
def load_file_int_matrix(name):
|
||||
with open(name, "r") as f:
|
||||
return load_int_matrix(f)
|
||||
|
||||
|
||||
def load_word_matrix(f):
|
||||
my_file = []
|
||||
for line in f:
|
||||
my_file.append(line.rstrip())
|
||||
return [x.split(" ") for x in my_file]
|
||||
|
||||
|
||||
def load_file_word_matrix(name):
|
||||
with open(name, "r") as f:
|
||||
return load_word_matrix(f)
|
||||
|
||||
|
||||
#############
|
||||
|
||||
|
||||
def rotate(WHAT, times=1):
|
||||
what = WHAT
|
||||
for x in range(times):
|
||||
@ -60,7 +70,6 @@ def rotate(WHAT, times=1):
|
||||
return what
|
||||
|
||||
|
||||
|
||||
@contextmanager
|
||||
def elapsed_timer():
|
||||
start = default_timer()
|
||||
|
Loading…
Reference in New Issue
Block a user