Trying to write a script for a video to explain some Julia programming concepts. Was trying to use the birthday “paradox” as example. It states that in a room of 23 ppl, there is a 50% chance that at least one pair of person will have the same birthday.
I am trying to write code to simulate this to confirm the results.
This is the fastest code I can come up with. It’s about 0.25s for one million simulations
I have used these tricks
@inbounds, pre-allocation to avoid repeated allocation. Customised, one-by-one randomly bday generation, to avoid having to generate all
n birthdays at once.
I wonder if there are other tricks? Interested in interesting tricks I have missed.
Interestingly I tried AutoPreAllocation.jl but it gave error, so that didn’t work.
# Birtyday paradox function atleast2_v3!(d, npersons) d .= false @inbounds d[rand(1:365)] = true @inbounds for _ in 2:npersons bday = rand(1:365) d[bday] && return true d[bday] = true end false end function simulate_bday_v3(npersons, ntimes=1_000_000) cnt = 0 d = falses(365) for _ in 1:ntimes cnt += atleast2_v3!(d, npersons) end cnt/ntimes end using BenchmarkTools @time simulate_bday_v3(23, 1_000_000)