Birthday paradox (jl)


using Plots
plotlyjs()

function iscollision(x)
    length(unique(x))<length(x)
end

function samplebirtday(n,i,tr=5000)
    j=0
    for _ in 1:tr
        iscollision(rand(1:n,i)) && (j+=1)
    end
    j/tr
end

function actualest(n,i)
    1-reduce(*,[1-j/n for j in 0:i-1])
end

function expest(n,i)
    C=√(-2*log(1-1/2))
    v=1-C*exp(-i*(i+1)/(2n))
    v>0 ? v : 0
end

function getprobs(n,tr=5000)
    R=[ 0 0 0 ]
    for i in 1:n
        R=[R ; [samplebirtday(n,i,tr) actualest(n,i) expest(n,i)] ]
    end
    R
end

function plotprobs(n,tr=5000)
    cv=ceil(√(2log(2)*n))
    m=getprobs(n,tr)
    plot(xrange=(0,n),yrange=(0,1))
    hline!([1/2],label="")
    vline!([cv,cv+2],label="")
    plot!(m,label=["Sample" "Actual" "Exp"])
end