Skip to content

Instantly share code, notes, and snippets.

@pawlos
Last active December 20, 2017 14:02
Show Gist options
  • Save pawlos/24c26762184837457c5b0cd9f4b8fe5f to your computer and use it in GitHub Desktop.
Save pawlos/24c26762184837457c5b0cd9f4b8fe5f to your computer and use it in GitHub Desktop.
Solution to Day 14: Disk Defragmentation
#aoc_d14.py
def knot_hash(inputstr):
skip_size = 0
inp = range(0,256)
ind = 0
for i in range(0,64):
lengths = [ord(c) for c in inputstr]
add = [17, 31, 73, 47, 23]
lengths = lengths + add
#print lengths
for l in lengths:
w = []
for i in range(ind,ind+l):
w.append(inp[i%len(inp)])
rev = w[::-1]
o = {}
for i in range(ind,ind+l):
o[i%len(inp)] = rev[i-ind]
n = [None]*len(inp)
for i in range(0,len(inp)):
if i in o:
n[i]= o[i]
else:
n[i] = inp[i]
inp = n
ind = (ind + (l + skip_size)) % len(inp)
skip_size += 1
res = ''
for i in range(0,16):
w = inp[i*16:(i+1)*16]
z = w[0]
for r in range(1,len(w)):
z = z ^ w[r]
res += '{:02x}'.format(z)
return res
sum_bits = 0
for i in range(128):
r = knot_hash("stpzcrnm-"+str(i))
sum_bits += bin(int(r,16)).count("1")
print i,r, sum_bits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment