Skip to content

Commit d95d277

Browse files
committed
Completed day 23 of year 2024
1 parent 73f8282 commit d95d277

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

2024/23.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
split_data = True
5+
completed = True
6+
raw_data = None # Not To be touched
7+
8+
def part1(data):
9+
pairings = {}
10+
for line in data:
11+
# print(line)
12+
a, b = line.split('-')
13+
if a not in pairings:
14+
pairings[a] = set()
15+
if b not in pairings:
16+
pairings[b] = set()
17+
18+
pairings[a].add(b)
19+
pairings[b].add(a)
20+
21+
# In order to find a triangle you simply take the intersection of pair[a] and pair[b]
22+
# This will give you the commons of pair a and pair b which would c. Therefore, a triangle.
23+
commons = set()
24+
for line in data:
25+
a, b = line.split('-')
26+
common = pairings[a] & pairings[b]
27+
for c in common:
28+
if a[0] != 't' and b[0] != 't' and c[0] != 't': continue
29+
tri = tuple(sorted([a,b,c]))
30+
commons.add(tri)
31+
32+
return len(commons)
33+
34+
def part2(data):
35+
pairings = {}
36+
for line in data:
37+
# print(line)
38+
a, b = line.split('-')
39+
if a not in pairings:
40+
pairings[a] = set()
41+
if b not in pairings:
42+
pairings[b] = set()
43+
44+
pairings[a].add(b)
45+
pairings[b].add(a)
46+
47+
# The below is what I implemented on my own. It works but is highly inefficient...
48+
"""
49+
def recurse(curr_set):
50+
if len(curr_set) == 0:
51+
return 0
52+
53+
return max(recurse(curr_set & pairings[i]) for i in curr_set) + 1
54+
55+
return recurse(set(pairings.keys()))
56+
"""
57+
58+
# Bron-Kerbosch algorithm with pivoting...
59+
def BronKerbosch2(R:set, P:set, X:set):
60+
if len(P) == 0 and len(X) == 0:
61+
return R
62+
63+
u = list(P | X)[0]
64+
max_R = set()
65+
max_len = 0
66+
for v in P - pairings[u]:
67+
r = BronKerbosch2(R | {v}, P & pairings[v], X & pairings[v])
68+
if len(r) > max_len:
69+
max_len = len(r)
70+
max_R = r
71+
P.remove(v)
72+
X.add(v)
73+
74+
return max_R
75+
76+
max_R = BronKerbosch2(set(), set(pairings.keys()), set())
77+
return ','.join(sorted(tuple(max_R)))

0 commit comments

Comments
 (0)