From day 10


In [7]:
function knot_hash_base(lens, size=256, rounds=1)
    i = 0
    skip = 0
    elem = collect(0:(size)-1)    
    for r = 1:rounds
        for l in lens
            elem = circshift(reverse(circshift(elem, -i), 1, l), i)
            i = (i + l + skip) % size
            skip += 1        
        end
    end    
    elem
end

function encode_str(values)
    vcat(map(Int, collect(values)), [17, 31, 73, 47, 23])
end

function encode_hexa(elem)
    elem = reshape(elem, (16, 16))
    elem = mapslices(c->reduce(xor,0,c), elem, 1)
    join(map(x->hex(x,2), elem))
end

function knot_hash(value)
    encode_hexa(knot_hash_base(encode_str(value), 256, 64))
end


Out[7]:
knot_hash (generic function with 1 method)

Part 1


In [38]:
function fragmentation_matrix(key)
    [[(c == '1' ? 1 : 0) for b in map(bits, hex2bytes(knot_hash(key*"-"*string(row)))) for c in collect(b)] for row=0:127]
end


Out[38]:
fragmentation_matrix (generic function with 1 method)

In [41]:
sum(sum(fragmentation_matrix("flqrgnkx")))


Out[41]:
8108

In [42]:
sum(sum(fragmentation_matrix("vbqugkhl")))


Out[42]:
8148

Part 2


In [67]:
function fill_region(m, r, c, region)
    if r>0 && r<129 && c>0 && c<129 && m[r][c]==1
        m[r][c] = region
        fill_region(m, r-1,   c, region)
        fill_region(m, r  , c-1, region)
        fill_region(m, r+1,   c, region)
        fill_region(m, r  , c+1, region)
    end
end        

function count_regions(key)
    m = fragmentation_matrix(key)
    region = 2
    for r=1:128
        for c=1:128
            if m[r][c] == 1
                fill_region(m, r, c, region)
                region += 1
            end
        end
    end
    region - 2
end


Out[67]:
count_regions (generic function with 1 method)

In [68]:
count_regions("flqrgnkx")


Out[68]:
1242

In [70]:
count_regions("vbqugkhl")


Out[70]:
1180

In [ ]: