I have the following code that runs in about 8 seconds:
using Random
DEBUG = false
PRISONERS = 100
ATTEMPTS = 50
function tryit()
a = [1:1:PRISONERS;]
a = shuffle(a)
for i in 1:PRISONERS
if DEBUG
println("prisoner $i")
end
count = 0
check = i
while count <= ATTEMPTS
count += 1
if a[check] == i
if DEBUG
println("Attempt $count: Checking box $check and found my number")
end
break
else
if DEBUG
println("Attempt $count: Checking box $check and found $(a[check])")
end
check = a[check]
end
end
if count > ATTEMPTS
if DEBUG
println("Prisoner $i failed to find his number in 50 attempts")
end
return false
end
end
return true
end
function main()
tries = 100000
success = 0.0
for i in 1:tries
if tryit()
success += 1
end
end
println("Ratio of success = $(success / tries)")
end
main()
Moving the global variables inside the function cuts the runtime to a tenth:
using Random
function tryit()
DEBUG = false
PRISONERS = 100
ATTEMPTS = 50
a = [1:1:PRISONERS;]
a = shuffle(a)
for i in 1:PRISONERS
if DEBUG
println("prisoner $i")
end
count = 0
check = i
while count <= ATTEMPTS
count += 1
if a[check] == i
if DEBUG
println("Attempt $count: Checking box $check and found my number")
end
break
else
if DEBUG
println("Attempt $count: Checking box $check and found $(a[check])")
end
check = a[check]
end
end
if count > ATTEMPTS
if DEBUG
println("Prisoner $i failed to find his number in 50 attempts")
end
return false
end
end
return true
end
function main()
tries = 100000
success = 0.0
for i in 1:tries
if tryit()
success += 1
end
end
println("Ratio of success = $(success / tries)")
end
main()
I could not reproduce the problem with a smaller code example. I am using Julia version 1.7.2 on Linux Mint.