1
0
Fork 0
adventofcode/2017/14/defrag.py

58 lines
1.5 KiB
Python
Executable File

#!/usr/bin/env python3
import sys
line = sys.argv[1]
def run(lengths, times):
numbers, current, skip = list(range(256)), 0, 0
for _ in range(times):
for length in lengths:
for i in range(length // 2):
first = (current + i) % len(numbers)
second = (current + length - 1 - i) % len(numbers)
numbers[first], numbers[second] = numbers[second], numbers[first]
current += length + skip
skip += 1
return numbers
def dense(numbers):
r = ""
for i in range(len(numbers) // 16):
num = 0
for j in range(16):
num ^= numbers[i*16+j]
r += hex(num)[2:].zfill(2)
return r
def knothash(text):
bytedata = [ord(n) for n in text] + [17, 31, 73, 47, 23]
return dense(run(bytedata, 64))
usedsquares, rows = 0, []
for i in range(128):
b = '{:0128b}'.format(int(knothash(line + "-" + str(i)), 16))
usedsquares += sum(map(int, b))
rows.append(list(map(int, b)))
print(usedsquares)
seenpos, count = set(), 0
def regionsearch(x, y):
if ((x, y)) in seenpos or not rows[x][y]:
return
seenpos.add((x, y))
if x > 0:
regionsearch(x - 1, y)
if y > 0:
regionsearch(x, y - 1)
if x < 127:
regionsearch(x + 1, y)
if y < 127:
regionsearch(x, y + 1)
for i in range(128):
for j in range(128):
if ((i, j)) in seenpos or not rows[i][j]:
continue
count += 1
regionsearch(i, j)
print(count)