diff --git a/day10.py b/day10.py index a444b48..7747e6e 100644 --- a/day10.py +++ b/day10.py @@ -13,6 +13,31 @@ def cycle(sequence: list, sizes: list, index: int = 0, skip_length: int = 0) -> return sequence, index, skip_length +def knot_hash(key: str, rounds: int = 64) -> str: + index = 0 + skip_length = 0 + sequence = list(range(256)) + key = [ord(x) for x in key] + key += [17, 31, 73, 47, 23] + + for i in range(rounds): + sequence, index, skip_length = cycle(sequence, key, index, skip_length) + + dense = [] + for m in range(16): + xor = 0 + for i in range(16): + xor ^= sequence[m * 16 + i] + + dense.append(xor) + + hex_string = "" + for v in dense: + hex_string += ("%x" % v).rjust(2, '0') + + return hex_string + + class Day(AOCDay): inputs = [ [ @@ -29,30 +54,7 @@ class Day(AOCDay): return sequence[0] * sequence[1] def part2(self) -> Any: - sizes = [] - for x in self.getInput().strip(): - sizes.append(ord(x)) - sizes += [17, 31, 73, 47, 23] - index = 0 - skip_length = 0 - sequence = list(range(256)) - - for i in range(64): - sequence, index, skip_length = cycle(sequence, sizes, index, skip_length) - - dense = [] - for m in range(16): - xor = 0 - for i in range(16): - xor ^= sequence[m * 16 + i] - - dense.append(xor) - - hex_string = "" - for v in dense: - hex_string += ("%x" % v).rjust(2, '0') - - return hex_string + return knot_hash(self.getInput().strip()) if __name__ == '__main__': diff --git a/day14.py b/day14.py new file mode 100644 index 0000000..aae8d0a --- /dev/null +++ b/day14.py @@ -0,0 +1,51 @@ +from tools.coordinate import Coordinate +from tools.grid import Grid + +from day10 import knot_hash +from tools.aoc import AOCDay +from typing import Any + + +class Day(AOCDay): + inputs = [ + [ + (8108, "input14_test"), + (8316, "input14") + ], + [ + (1242, "input14_test"), + (1074, "input14") + ] + ] + + def part1(self) -> Any: + key_start = self.getInput().strip() + '-' + count = 0 + for x in range(128): + hash = knot_hash(key_start + str(x)) + bin_hash = bin(int(hash, 16))[2:].zfill(128) + count += bin_hash.count('1') + return count + + def part2(self) -> Any: + key_start = self.getInput().strip() + '-' + grid = Grid() + for y in range(128): + hash = knot_hash(key_start + str(y)) + bin_hash = bin(int(hash, 16))[2:].zfill(128) + for x, c in enumerate(bin_hash): + grid.set(Coordinate(x, y), c == '1') + + count = 0 + ignore_list = [] + for c in grid.getActiveCells(): + if c not in ignore_list: + count += 1 + ignore_list += grid.getActiveRegion(c) + + return count + + +if __name__ == '__main__': + day = Day(2017, 14) + day.run(verbose=True) diff --git a/inputs/input14 b/inputs/input14 new file mode 100644 index 0000000..fc4bcc8 --- /dev/null +++ b/inputs/input14 @@ -0,0 +1 @@ +ljoxqyyw diff --git a/inputs/input14_test b/inputs/input14_test new file mode 100644 index 0000000..e0ffae2 --- /dev/null +++ b/inputs/input14_test @@ -0,0 +1 @@ +flqrgnkx