Added 2017/25 Part 1

This commit is contained in:
2024-11-30 23:15:29 +01:00
parent fcd169e923
commit 4cb6a22981
5 changed files with 241 additions and 18 deletions
+29 -15
View File
@@ -1,5 +1,6 @@
#!/bin/python3
import sys,re
from copy import deepcopy
from pprint import pprint
sys.path.insert(0, '../../')
from fred import list2int, lprint,get_re
@@ -14,6 +15,25 @@ log = True
# #
#########################################
def find_match(comp:list,match:str,result:list):
i_match = get_re(r"^(\d+)\/(\d+)$",match)
#print(comp,match)
comp = [i for i in comp if i != match]
#print(comp,result)
for i in result:
try:
comp = [j for j in comp if j != i]
except:
print(i,'cant be removed from',j)
for j in comp:
j_match = get_re(r"^(\d+)\/(\d+)$",j)
#print(match,j)
#input()
if i_match.group(2) == j_match.group(1) or i_match.group(2) == j_match.group(2):
result.append(j)
find_match(comp[:],match,result[:])
return result
if part == 1:
components = []
with open(input_f) as file:
@@ -21,25 +41,19 @@ if part == 1:
components.append(line.rstrip())
lprint(components,log)
original_comp = deepcopy(components)
pairs = []
result = []
for i in components:
t = []
i_match = get_re(r"^(\d+)\/(\d+)$",i)
for i in components[:]:
print(i)
if i[0] == '0':
result.append(find_match(original_comp,i,[i]))
if i_match.group(1) == '0': #can start
pairs.append([i])
for j in (components):
j_match = get_re(r"^(\d+)\/(\d+)$",j)
if i_match.group(2) == j_match.group(1) or i_match.group(2) == j_match.group(2):
#if i[2] == j[0] or i[2] == j[2]:
t.append(j)
pairs.append(t)
lprint(t,log)
input()
lprint(pairs,log)
pprint(result)
#nput()
#lprint(pairs,log)
+58
View File
@@ -0,0 +1,58 @@
from collections import defaultdict
import pprint
def build_graph(pairs):
graph = defaultdict(list)
for pair in pairs:
a, b = map(int, pair.split('/'))
graph[a].append(b)
graph[b].append(a)
return graph
def find_all_paths(graph, start, visited=None, path=None):
if visited is None:
visited = set()
if path is None:
path = []
visited.add(start)
path.append(start)
paths = [list(path)] # Store the current path as a possible connection
for neighbor in graph[start]:
if neighbor not in visited:
paths.extend(find_all_paths(graph, neighbor, visited.copy(), path.copy()))
return paths
def count_connections(pairs):
graph = build_graph(pairs)
all_paths = []
for pair in pairs:
a, b = map(int, pair.split('/'))
paths_a = find_all_paths(graph, a)
paths_b = find_all_paths(graph, b)
# Combine paths starting from both nodes in the pair
for path in paths_a:
if b in path:
all_paths.append(path)
for path in paths_b:
if a in path:
all_paths.append(path)
# Remove duplicate paths
unique_paths = {tuple(path) for path in all_paths}
return len(unique_paths), unique_paths
# Example usage
pairs = ['0/2','2/2','2/3','3/4','3/5','0/1','10/1','9/10']
connection_count, connections = count_connections(pairs)
print(f"Number of connections: {connection_count}")
print("Connections:")
for connection in connections:
print(connection)
pprint(connections)