I am new to this language, tried a few speed up tips and this is the best i got. Is there anything else that can be done to get a significant performance increase? Can you show me how?
using Plots, Printf, OffsetArrays
function loops(nn::Integer, kk::Integer)
if nn < 0 || kk <= 0
return nothing
end
if nn > 0 && nn < kk
return nothing
end
_loops(Float64(nn),Float64(kk))
end
function _loops(n::Float64, k::Float64)
if k == 1 || n == 0
return 1.0
end
cnt = 0.0
for j = 1:floor(n/k)
recur = 0.0
m = min(k-1, n-j*k)
if m == 0
m = 1.0
end
for t = 1:m
recur += _loops(n-j*k, t)
end
cnt += recur*(fac[Int(n)]/fac[Int(n-j*k)])/(fac[Int(j)]*(k^j))
end
return cnt
end
n = 100
const fac = OffsetArray([1.0; cumprod(1:Float64(n))], 0:n)
@time begin
y = Vector{Float64}(undef, n)
for i = 1:n
y[i] = loops(n,i)/fac[n]
end
end
y1 = sum(y[1:Int(n/2)])
y2 = sum(y[Int(n/2)+1:n])
colors = [ifelse(i<=Int(n/2), "green", "red") for i=1:n]
#colors = fill("red", n)
#colors[1:Int(n/2)] .= "green"
mm = Plots.mm
bar( y,
margin=7mm,
size=(1000,667),
xticks=1:2:n,
xrot=90,
color=colors,
label="$(@sprintf("%.0f",y1*100))%",
legendfontsize=16,
titlefontsize=24,
guidefontsize=16,
tickfontsize=8
)
bar!( [1],[0],
label="$(@sprintf("%.0f",y2*100))%",
color=colors[n]
)
title!("\n$n Prisoners")
xlabel!("Longest Loop")
ylabel!("Probability")