|
@@ -0,0 +1,50 @@
|
|
1
|
+import functools
|
|
2
|
+import itertools
|
|
3
|
+import operator
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+def reverse_slice(input, start, length):
|
|
7
|
+ """Reverses a slice of the input list, wrapping around if necessary."""
|
|
8
|
+ output = list(input)
|
|
9
|
+ for i, pos in enumerate(range(start, start + length)):
|
|
10
|
+ output[pos % len(output)] = input[(start + length - i - 1) % len(output)]
|
|
11
|
+ return output
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+def knot_hash_rounds(lengths, count=1):
|
|
15
|
+ """Applies a number of rounds of the knot hash algorithm (see day 10)."""
|
|
16
|
+ position, skip, data = 0, 0, list(range(256))
|
|
17
|
+ for _ in range(count):
|
|
18
|
+ for length in lengths:
|
|
19
|
+ data = reverse_slice(data, position, length)
|
|
20
|
+ position += length + skip
|
|
21
|
+ skip += 1
|
|
22
|
+ return data
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+def group(n, iterable):
|
|
26
|
+ """Collates the iterable into groups n items long."""
|
|
27
|
+ # https://docs.python.org/3.1/library/itertools.html#recipes
|
|
28
|
+ args = [iter(iterable)] * n
|
|
29
|
+ return itertools.zip_longest(*args)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+def knot_hash(seed):
|
|
33
|
+ """The knot has algorithm (day 10). Output is a hex string."""
|
|
34
|
+ lengths = list(map(ord, seed.strip())) + [17, 31, 73, 47, 23]
|
|
35
|
+ sparse_hash = knot_hash_rounds(lengths, 64)
|
|
36
|
+ dense_hash = [functools.reduce(operator.xor, g) for g in group(16, sparse_hash)]
|
|
37
|
+ return "".join(f"{c:02x}" for c in dense_hash)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+def add_connected_components(sets, links, to_add=None):
|
|
41
|
+ """
|
|
42
|
+ Updates the given collection of sets to include a new group of connected components.
|
|
43
|
+
|
|
44
|
+ Existing sets that overlap with the given `links` are removed and conjoined into a new superset along with the
|
|
45
|
+ `to_add` items specified. If `to_add` is not specified then the `links` are added in their place.
|
|
46
|
+ """
|
|
47
|
+ overlapping = [s for s in sets if any(link in s for link in links)]
|
|
48
|
+ for overlap in overlapping:
|
|
49
|
+ sets.remove(overlap)
|
|
50
|
+ sets.append(functools.reduce(set.union, overlapping, set(to_add if to_add is not None else links)))
|