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]:
In [2]:
dance('a':'e', split("s1,x3/4,pe/b", ","), 1)
Out[2]:
In [3]:
open("inputs/day16.txt") do fd
@time dance('a':'p', split(strip(readstring(fd)),","), 1)
end
Out[3]:
In [4]:
open("inputs/day16.txt") do fd
@time dance('a':'p', split(strip(readstring(fd)),","), 1000000000)
end
Out[4]:
In [ ]: