I am starting with a list of length n that contains all -1's. For instance, when n = 6
the list is {-1, -1, -1, -1, -1, -1}
. I pick a random integer from 1 to n and toggle the element by multiplying by -1. In the given list, if I pick the third element, the new list would be {-1, -1, 1, -1, -1, -1}
. I continue in this manner, picking an element randomly and toggling it from plus to minus or minus to plus. I wish to know how long it will take for the list to have all 1's. How long will it take to become {1, 1, 1, 1, 1, 1}
?
My code is:
toggle[box_, n_] :=
Block[{r, h = box},
r = RandomInteger[{1, n}];
h[[r]] = -h[[r]];
h]
n = 6;
trials = 40000;
box = ConstantArray[-1, n];
ans =
Table[sbox = box;
(NestWhileList[toggle[#, n] &,
sbox,
Total[#] != n &] // Length) - 1,
{trials}];
Mean[ans] // N
The exact answer for this one is 416 / 5. I am getting around 83 for my simulation, but it is deadly slow. Can I speed it up?
Total
of this list, we could also analyse the discrete time discrete state Ehrenfest process (which is apparently hard to google). I think the distribution of the hitting time may be quite nice, in which a single call toRandomVariate
may suffice... $\endgroup$