Part 1


In [1]:
function dance(status, steps, reps)
    
    r = 1
    seen = Dict()    
    status = collect(status)
    while r<=reps
        for step in steps
            if step[1] == 's'
                # SPIN
                a, = match(r"s([0-9]+)", step).captures                
                status = circshift(status, a[1])
            elseif step[1] == 'x'
                # EXCHANGE
                a, b = match(r"x([0-9]+)/([0-9]+)", step).captures
                a = parse(Int, a) + 1
                b = parse(Int, b) + 1
                ca = status[a]
                cb = status[b]
                status[a] = cb
                status[b] = ca
            elseif step[1] == 'p'
                # PARTNER
                a, b = match(r"p([a-z])/([a-z])", step).captures            
                a = findfirst(status, a[1])
                b = findfirst(status, b[1])
                ca = status[a]
                cb = status[b]
                status[a] = cb
                status[b] = ca
            end
        end
        
        str_status = join(status)
        if haskey(seen, str_status)
            target = reps % (r - seen[str_status])
            for (k, v) in seen
                if v == target
                    return k
                end
            end
        else
            seen[str_status] = r
        end
        r += 1
    end
    join(status)
end


Out[1]:
dance (generic function with 1 method)

In [2]:
dance('a':'e', split("s1,x3/4,pe/b", ","), 1)


Out[2]:
"ecdab"

In [3]:
open("inputs/day16.txt") do fd
    @time dance('a':'p', split(strip(readstring(fd)),","), 1)
end


  0.007905 seconds (79.18 k allocations: 4.645 MiB)
Out[3]:
"kfmaegpbclnjhodi"

Part 2


In [4]:
open("inputs/day16.txt") do fd
    @time dance('a':'p', split(strip(readstring(fd)),","), 1000000000)
end


  0.260832 seconds (2.15 M allocations: 123.111 MiB, 6.30% gc time)
Out[4]:
"ajcdefghpkblmion"

In [ ]: