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

plotting - Filling between two spheres in SphericalPlot3D

Manipulate[ SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, Mesh -> None, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], {n, 0, 1}] I cant' seem to be able to make a filling between two spheres. I've already tried the obvious Filling -> {1 -> {2}} but Mathematica doesn't seem to like that option. Is there any easy way around this or ... Answer There is no built-in filling in SphericalPlot3D . One option is to use ParametricPlot3D to draw the surfaces between the two shells: Manipulate[ Show[SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], ParametricPlot3D[{ r {Sin[t] Cos[1.5 Pi], Sin[t] Sin[1.5 Pi], Cos[t]}, r {Sin[t] Cos[0 Pi], Sin[t] Sin[0 Pi], Cos[t]}}, {r, 1, 2 - n}, {t, 0, Pi}, PlotStyle -> Yellow, Mesh -> {2, 15}]], {n, 0, 1}]

plotting - Plot 4D data with color as 4th dimension

I have a list of 4D data (x position, y position, amplitude, wavelength). I want to plot x, y, and amplitude on a 3D plot and have the color of the points correspond to the wavelength. I have seen many examples using functions to define color but my wavelength cannot be expressed by an analytic function. Is there a simple way to do this? Answer Here a another possible way to visualize 4D data: data = Flatten[Table[{x, y, x^2 + y^2, Sin[x - y]}, {x, -Pi, Pi,Pi/10}, {y,-Pi,Pi, Pi/10}], 1]; You can use the function Point along with VertexColors . Now the points are places using the first three elements and the color is determined by the fourth. In this case I used Hue, but you can use whatever you prefer. Graphics3D[ Point[data[[All, 1 ;; 3]], VertexColors -> Hue /@ data[[All, 4]]], Axes -> True, BoxRatios -> {1, 1, 1/GoldenRatio}]

plotting - Mathematica: 3D plot based on combined 2D graphs

I have several sigmoidal fits to 3 different datasets, with mean fit predictions plus the 95% confidence limits (not symmetrical around the mean) and the actual data. I would now like to show these different 2D plots projected in 3D as in but then using proper perspective. In the link here they give some solutions to combine the plots using isometric perspective, but I would like to use proper 3 point perspective. Any thoughts? Also any way to show the mean points per time point for each series plus or minus the standard error on the mean would be cool too, either using points+vertical bars, or using spheres plus tubes. Below are some test data and the fit function I am using. Note that I am working on a logit(proportion) scale and that the final vertical scale is Log10(percentage). (* some test data *) data = Table[Null, {i, 4}]; data[[1]] = {{1, -5.8}, {2, -5.4}, {3, -0.8}, {4, -0.2}, {5, 4.6}, {1, -6.4}, {2, -5.6}, {3, -0.7}, {4, 0.04}, {5, 1.0}, {1, -6.8}, {2, -4.7}, {3, -1.