Skip to main content

random - Simulating Theatre puzzle


I have been trying to simulate the process of the theatre puzzle from the Joy of X (Strogatz). The puzzle, and some relevant material are here.


My simplistic coding for this process follows:


seatchoice[u_] := Module[{r, s}, r = RandomReal[]; s = RandomChoice[u];
If[And[MemberQ[u, s + 1], MemberQ[u, s - 1]],
If[r <= 0.5, Complement[u, {s, s + 1}],Complement[u, {s - 1, s}]],

If[MemberQ[u, s + 1], Complement[u, {s, s + 1}],
If[MemberQ[u, s - 1], Complement[u, {s - 1, s}],
If[And @@ (# >= 2 & /@ Differences[Sort[u]]), u,
If[Length[u] == 0, u,
seatchoice[u]]]]]]];
emptyfraction[v_] := N@Length[FixedPoint[seatchoice, Range[v]]]/v;

I have consistently found despite simulations for 100, 1000,2000 seats (recursion and iteration limits are exceeded for large inputs) that expectations are consistently approx 0.124 (versus expected approx 0.135) with narrowing bounds with increasing sample size or sample number. Further, the closed form for the expectation of number of empty seats suggests this approaches limit from above.


Question: Is this related to dependencies/other in my coding of puzzle; related to pseudorandom number generation in Mathematica; other issues


A visualization from my code is appended. enter image description here




Answer



This answer is going to be a bit of a sprawl. Please read on.


I am going to present several methods of simulation, hopefully in increasing order of performance.


Method 1


We can carry out the filling of seats, at least as I understand the puzzle, quite literally like this:


fillseats[seats_List] :=
ReplacePart[seats,
{{1}, {2}} + RandomChoice @ ReplaceList[seats, {a___, 0, 0, ___} :> Length@{a}] -> 1
]


sim1[n_] := Tr @ Quiet @ FixedPoint[fillseats, 0 ~ConstantArray~ n]

Test:


sim1[1000] // Timing


{1.061, 866}

This works by first filling a list of length n with zeros, then repeatedly finding every appearance of the sequence 0, 0, randomly picking one of them, and replacing both zeros with ones. When there are no more seats to fill the simulation stops.


Tr is used to find the sum of the resultant vector, in other words the number of seats filled. It can be left out to see the actual "seat" filling.





Method 2


Observing the mechanics of the simulation above we can see that we are always operating on pairs of positions. For example, with seven total seats there are these possible seating positions:


{{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}}

We can represent this by the first value of each pair: {1, 2, 3, 4, 5, 6}. When a pair of seats is filled we remove the index from the list and any remaining indexes that are $index\pm 1$. The simulation is stopped when the index list does not change, signifying that it is empty.


2 (Length[#] - 2) & is used to count the filled seats from the number of times seats are filled. (-2 is needed to account for the starting and ending values in FixedPointList that do not represent fills.)


sim2[n_] :=
FixedPointList[
DeleteCases[#2, # | # + 1 | # - 1] &[Quiet@RandomChoice@#, #] &,

Range[n - 1]
] // 2 (Length[#] - 2) &

This method is a lot faster than sim1. For example, 100 simulations each filling 1,000 seats:


1` - Sum[sim2[1000], {100}]/(100*1000) // Timing


{2.043, 0.13656}

We can rewrite sim2 in a way that proves faster for simulations with a large number of seats. Here the index list of pairs, e.g. {1, 2, 3, 4, 5, 6} is replaced by a fixed-length vector, filled with ones: {1, 1, 1, 1, 1, 1}. SparseArray Properties are used to quickly find the positions of all remaining ones. Update: moved conversion to Sparse Array outside the loop.



sim3[n_] :=
Module[{x, n1 = n - 1, i = 0},
x = SparseArray @ ConstantArray[1, {n1}];
While[Tr@x =!= 0,
i++;
x[[Clip[{-1, 0, 1} + RandomChoice @ x["AdjacencyLists"], {1, n1}]]] = 0
];
2 i
]


Timings with 10,000 seats:


sim2[10000] // Timing
sim3[10000] // Timing


{1.919, 8624}

{0.172, 8694}




Method 3


I believe it is possible to pick the order of seat filling from the beginning and achieve the same filling probability. I generate all possible seating pairs with Partition[Range@n, 2, 1], randomize them, then simply try filling those seats in that order, moving to the next one if any requested seat is already filled.


sim4 =
Compile[{{n, _Integer}},
Module[{seats, trys},
seats = ConstantArray[0, n];
trys = RandomSample @ Partition[Range@n, 2, 1];
Do[If[seats[[i]] === {0, 0}, seats[[i]] = {1, 1}], {i, trys}];
Tr @ seats
]

];

Filling one million seats:


sim4[1*^6] // Timing


{0.359, 864766}

One thousand simulations of filling 10,000 seats:


Sum[sim4[10000], {1000}] // Timing



{3.26, 8645808}

Proportion of empty seats:


1` - (8645808 / 1*^7)


0.135419


Comments

Popular posts from this blog

functions - Get leading series expansion term?

Given a function f[x] , I would like to have a function leadingSeries that returns just the leading term in the series around x=0 . For example: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x)] x and leadingSeries[(1/x + 2 + (1 - 1/x^3)/4)/(4 + x)] -(1/(16 x^3)) Is there such a function in Mathematica? Or maybe one can implement it efficiently? EDIT I finally went with the following implementation, based on Carl Woll 's answer: lds[ex_,x_]:=( (ex/.x->(x+O[x]^2))/.SeriesData[U_,Z_,L_List,Mi_,Ma_,De_]:>SeriesData[U,Z,{L[[1]]},Mi,Mi+1,De]//Quiet//Normal) The advantage is, that this one also properly works with functions whose leading term is a constant: lds[Exp[x],x] 1 Answer Update 1 Updated to eliminate SeriesData and to not return additional terms Perhaps you could use: leadingSeries[expr_, x_] := Normal[expr /. x->(x+O[x]^2) /. a_List :> Take[a, 1]] Then for your examples: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x), x] leadingSeries[Exp[x], x] leadingSeries[(1/x + 2 + (1 - 1/x...

How to thread a list

I have data in format data = {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}} Tableform: I want to thread it to : tdata = {{{a1, b1}, {a2, b2}}, {{a1, c1}, {a2, c2}}, {{a1, d1}, {a2, d2}}} Tableform: And I would like to do better then pseudofunction[n_] := Transpose[{data2[[1]], data2[[n]]}]; SetAttributes[pseudofunction, Listable]; Range[2, 4] // pseudofunction Here is my benchmark data, where data3 is normal sample of real data. data3 = Drop[ExcelWorkBook[[Column1 ;; Column4]], None, 1]; data2 = {a #, b #, c #, d #} & /@ Range[1, 10^5]; data = RandomReal[{0, 1}, {10^6, 4}]; Here is my benchmark code kptnw[list_] := Transpose[{Table[First@#, {Length@# - 1}], Rest@#}, {3, 1, 2}] &@list kptnw2[list_] := Transpose[{ConstantArray[First@#, Length@# - 1], Rest@#}, {3, 1, 2}] &@list OleksandrR[list_] := Flatten[Outer[List, List@First[list], Rest[list], 1], {{2}, {1, 4}}] paradox2[list_] := Partition[Riffle[list[[1]], #], 2] & /@ Drop[list, 1] RM[list_] := FoldList[Transpose[{First@li...

front end - keyboard shortcut to invoke Insert new matrix

I frequently need to type in some matrices, and the menu command Insert > Table/Matrix > New... allows matrices with lines drawn between columns and rows, which is very helpful. I would like to make a keyboard shortcut for it, but cannot find the relevant frontend token command (4209405) for it. Since the FullForm[] and InputForm[] of matrices with lines drawn between rows and columns is the same as those without lines, it's hard to do this via 3rd party system-wide text expanders (e.g. autohotkey or atext on mac). How does one assign a keyboard shortcut for the menu item Insert > Table/Matrix > New... , preferably using only mathematica? Thanks! Answer In the MenuSetup.tr (for linux located in the $InstallationDirectory/SystemFiles/FrontEnd/TextResources/X/ directory), I changed the line MenuItem["&New...", "CreateGridBoxDialog"] to read MenuItem["&New...", "CreateGridBoxDialog", MenuKey["m", Modifiers-...