# Random walk in limited range [duplicate]

m = {{1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1,
1}, {1, 1}, {1, 1}};
m2 = {{1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1,
1}, {1, 1}, {1, 1}};
Manipulate[
Do[
m[[n]] = m[[n]] + RandomChoice[{{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {0, 0}}];
, {n, 10}];
Do[
m2[[n]] = m2[[n]] + RandomChoice[{{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {0, 0}}];
, {n, 10}];
Show[ListPlot[m, PlotStyle -> Red]
, ListPlot[m2, PlotStyle -> {PointSize[0.03]}]]
, {n, 1, 20}]


This is pseudo-randomwalk. I want to plot in only square (0,0),(100,0),(0,100),(100,100). Please teach me the random walk in limited range.

## marked as duplicate by C. E., RunnyKine, user9660, m_goldberg, MarcoBApr 4 '16 at 12:51

• Here are links to learn from, have you been there? mathematica.stackexchange.com/search?q=random+walk – Kuba Apr 4 '16 at 7:16
• Do you think it is a duplicate question? Bounded random walk – Kuba Apr 4 '16 at 7:17
• I don't think so. Sorry. – Shakariky Apr 4 '16 at 7:33
• As I see it, the only necessary modification in m_goldberg's code for your purposes is to modify the definition for nxt: nxt = pt + RandomChoice[{{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {0, 0}}] – J. M. will be back soon Apr 4 '16 at 7:57
• RegionMember not supported in version 9. What should I change code? – Shakariky Apr 4 '16 at 8:55

This modification of m_goldberg's code should work on version 9.0

nextPt[pt_, r_, bounds_] :=
Block[{nxt = pt + r {Cos[#], Sin[#]} &[RandomReal[2. π]]},
If[And @@ Thread[bounds[[1]] <= nxt <= bounds[[2]]], Return[nxt]];
nextPt[pt, r, bounds]];
walk[start : {_Real, _Real}, range : {_Real, _Real}, r_Real?Positive,
steps_Integer?Positive] :=
Module[{bounds}, bounds = {start - range/2, start + range/2};
NestList[nextPt[#, r, bounds] &, start, steps]];
walkAnimation[path_, opts : OptionsPattern[]] :=
ListAnimate[
Table[
Graphics[{Line[path[[;; n]]],
Red, Disk[First[path], Scaled[.015]],
Blue, Disk[path[[n]], Scaled[.015]]},
opts, Frame -> True],
{n, Length@path}], 10];

walkAnimation[walk[{50., 50.}, {100., 100.}, 5., 200],
PlotRange -> {{0, 100}, {0, 100}}]


• Glad to help, welcome to the site, take the tour, come back if you have other troubles, and try to answer questions when you can. Next time you have a question, if you are still using a previous version of Mathematica, be sure to include that in the quesiton, as it can help get to the pertinent info more quickly. – Jason B. Apr 4 '16 at 9:35