Derangements and Sampling without Replacement


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


WARNING: Method definition derangement(Int64) in module Main at In[4]:2 overwritten at In[18]:2.
Out[18]:
derangement (generic function with 1 method)

In [24]:
derangement(5)


Out[24]:
5-element Array{Int64,1}:
 3
 5
 2
 1
 4