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:

Of course better code welcome.