-
Notifications
You must be signed in to change notification settings - Fork 0
/
cardtricksim.jl
78 lines (66 loc) · 1.74 KB
/
cardtricksim.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using Random, StatsBase
suit = [collect(1:9); [1, 1, 1, 1]]
deck = repeat(suit,4)
function walk(deck,start)
while start + deck[start] <= length(deck)
start = start + deck[start]
end
return start
end
function couples!(deck)
shuffle!(deck)
starts = sample(1:5,2; replace=false)
end1 = walk(deck,starts[1])
end2 = walk(deck,starts[2])
return end1 == end2
end
function sim!(N,deck)
successes = 0.0
for i in 1:N
successes += couples!(deck)
end
rate = successes / N
v = rate * (1-rate)*N
s = sqrt(v)
se = s/N
return (lb = rate - 1.96*se, p = rate, ub=rate+1.96*se)
end
sim!(10,deck)
@time sim!(1_000_000,deck)
@profview sim!(1_000_000,deck)
# we can eke out a few percent from cutting the loop short as soon as the
# two positions are the same ... but it doesn't help much. Almost all the time is spent
# in the shuffle! function, and generating random numbers
function sim2(N)
deck = repeat([collect(1:9); [1,1,1,1]],4)
successes = 0.0
l = length(deck)
for i in 1:N
shuffle!(deck)
pos = sample(1:5,2)
end1 = false; end2=false;
while pos[1] != pos[2] && (!end1 || !end2)
if pos[1] + deck[pos[1]] <= l
pos[1] += deck[pos[1]]
else
end1 = true
end
if pos[2] + deck[pos[2]] <= l
pos[2] += deck[pos[2]]
else
end2 = true
end
end
if pos[1] == pos[2]
successes += 1.0
end
end
rate = successes / N
v = rate * (1.0-rate)*N
s = sqrt(v)
se = s/N
return (lb = rate - 1.96*se, p = rate, ub=rate+1.96*se)
end
sim2(10)
@time sim2(10_000_000)
@profview sim2(1_000_000)