Home > Mathematica > The Princess Revisited

The Princess Revisited

I enjoyed the Princess puzzle but lost the code I wrote. As an exercise, I approached it again…feeling in a code sharing mood,


sa = SparseArray[{{1, 2} -> 1, {17, 16} -> 1, Band[{2, 1}] -> 1/2,
Band[{2, 3}, {16, 17}] -> 1/2}, {17, 17}];
dm[p_] :=
DiscreteMarkovProcess[ReplacePart[ConstantArray[0, 17], p -> 1], sa]
sol = Thread[{Range[0, 29], Join[Range[2, 16], Reverse@Range[2, 16]]}];
func[n_] := Module[{rp = RandomFunction[dm[n], {0, 29}], pt},
pt = Intersection[rp["Paths"][[1]], sol];
ListPlot[{rp, sol}, PlotStyle -> {Black, Red}, Joined -> True,
Frame -> True,
FrameTicks -> {Table[{j, j + 1}, {j, 0, 29, 2}], Automatic},
PlotLabel ->
Row[Style[#, Bold] & /@ {"Princess starts in room: ", n}],
FrameLabel -> {"Day", "Room"}, Background -> LightOrange,
Epilog -> {Yellow, EdgeForm[Black], Disk[#, 0.5] & /@ pt}]]

and for simulation:

sim[num_] := Transpose[Table[func[#], {num}] & /@ Range[17]]

100 simulations:

princess

Of course better code welcome.

Advertisements
Categories: Mathematica
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: