Implement heuristic hands-free solution for day 25 that I came up with while falling asleep.

This commit is contained in:
2024-01-25 21:42:08 -05:00
parent cd00f46b77
commit 0d1eff4f00

59
d25.py
View File

@@ -16,7 +16,7 @@ def plot(graph):
plt.show()
def solve_non_hands_free(input: Input, second=False):
def solve_non_hands_free(input: Input):
graph = {}
for line in input.lines():
source, targets = line.split(":")
@@ -50,10 +50,67 @@ def solve_non_hands_free(input: Input, second=False):
return len(seen) * (len(graph) - len(seen))
from random import choice
from collections import deque
def solve(input: Input):
graph = {}
edges = {}
for line in input.lines():
src, dsts = line.split(":")
dsts = dsts.strip().split(" ")
if not src in graph:
graph[src] = []
for dst in dsts:
graph[src].append(dst)
if not dst in graph:
graph[dst] = []
graph[dst].append(src)
edge = tuple(sorted([src, dst]))
edges[edge] = 0
for i in range (1000):
first_node = choice(list(graph.keys()))
seen = set([first_node])
visit = deque([first_node])
while visit:
node = visit.popleft()
for nb in graph[node]:
if not nb in seen:
seen.add(nb)
visit.append(nb)
edge = tuple(sorted([node, nb]))
edges[edge] += 1
most_visited = sorted(edges.items(), key=lambda t: t[1], reverse=True)[:3]
# for node, count in most_visited:
# print(node, count)
for (a, b), _ in most_visited:
graph[a].remove(b)
graph[b].remove(a)
to_visit = [choice(list(graph.keys()))]
seen = set(to_visit)
while to_visit:
node = to_visit.pop()
for nb in graph[node]:
if not nb in seen:
seen.add(nb)
to_visit.append(nb)
return len(seen) * (len(graph) - len(seen))
def main():
DAY_INPUT = "i25.txt"
print("Solution 1:", solve_non_hands_free(Input(DAY_INPUT)))
print("Solution 1:", solve(Input(DAY_INPUT)), "(hands-free)")
if __name__ == "__main__":