@Seif_Shebl’s code does not count the draws, that’s why the answer comes out wrong. The phrasing of the problem itself on the Project Euler page was a bit unclear.
Here’s a version that gives you the right answer, and is ~2x as fast as @Seif_Shebl’s one. It avoids creating any arrays at all:
function eultest(n)
count = 0
for trials in 1:n
p1 = sum(rand(1:4) for _ in 1:9)
p2 = sum(rand(1:6) for _ in 1:6)
count += (p1 > p2)
end
return count / n
end
It uses a generator for creating the sums, so zero allocations. Also, you can avoid branches (if
or &&
) by realizing that you can do count += (p1 > p2)
. This works because n + false == n+0
while n + true = n+1
.
In order to get the correct number of significant digits, you should probably have some convergence criterion, so that you can tell when to stop iterating. Have you given any thought to that?