In [18]:
function derangement(n::Int64)
a = collect(1:n)
for i = n:-1:3
@inbounds j = a[i] > i ? rand(1:i) : rand(1:(i - 1))
@inbounds a[[j, i]] .= a[[i, j]]
end
a[[2, 1]] .= a[[1, 2]]
return a
end
Out[18]:
In [24]:
derangement(5)
Out[24]: