aoc_source(day =8, part =2)input=aoc_read(day =8)aoc_run(solve_day8_part2(input))
Elapsed: 1.854 seconds
Memory: 361623 KB
— Python Day 8 Part 1 —
from math import dist, prodimport networkx as nxdef solve_day8_part1(text, n_edges =1000): coords = [line.split(",") for line in text] coords = [[int(x) for x in box] for box in coords] edges = []for i inrange(len(coords)):for j inrange(len(coords)):if i < j: box_1, box_2 = coords[i], coords[j] edge_len = dist(box_1, box_2) edges += [[i, j, edge_len]] edges.sort(key =lambda x : x[2]) edges = edges[:n_edges] edges = [edge[:2] for edge in edges] # remove distances uf = nx.utils.UnionFind()for box_1, box_2 in edges: uf.union(box_1, box_2) groups =list(uf.to_sets()) sizes = [len(g) for g in groups] sizes.sort(reverse=True)return(prod(sizes[:3]))
Run
aoc_source(day =8, part =1)input= aoc_read(day =8)result = aoc_run("solve_day8_part1(input)")
Elapsed: 2.906 seconds
Memory: 77395 KB
— Python Day 8 Part 2 —
from math import distimport networkx as nxdef solve_day8_part2(text): coords = [line.split(",") for line in text] coords = [[int(x) for x in box] for box in coords] n_boxes =len(coords) edges = []for i inrange(len(coords)):for j inrange(len(coords)):if i < j: box_1, box_2 = coords[i], coords[j] edge_len = dist(box_1, box_2) edges += [[i, j, edge_len]] edges.sort(key =lambda x : x[2]) edges = [edge[:2] for edge in edges] # remove distances uf = nx.utils.UnionFind() n_circuits = n_boxesfor box_1, box_2 in edges:# union if boxes not already in same circuitif uf[box_1] != uf[box_2]: uf.union(box_1, box_2) n_circuits -=1if n_circuits ==1:return(coords[box_1][0] * coords[box_2][0])
Run
aoc_source(day =8, part =2)input= aoc_read(day =8)result = aoc_run("solve_day8_part2(input)")