A Random Walk

By Mariam Al-Hawaj

A random walk is a mathematical formalization of a path that consists of a succession of random steps.
In this program, I will show random walks in 2D and 3D, as well as self avoiding random walks in 3D.

Random Walks in 2D

Here, we draw the random walk in 2D using “ListPlot” and “PlotJointed”. Notice that “FoldList” is used to iterate the addition function to create the walk.

origin={0,0};
ListPlot[With[{k=4,l=80},SeedRandom[1];t=Table[{Cos[Pi x/2],Sin[ Pi x/2]},{x,0,k}];
FoldList[Plus,origin,Table[t[[Random[Integer,{1,k}]]],{l}]]],PlotJoined->True,PlotRange->All,AspectRatio->Automatic]

Here, we draw the random walk in 2D using the same program above. However, “Graphics” is used instead of the “ListPlot”.

origin={0,0};
walk[n_]:=With[{c=Max[First/@Abs[n]],r=Max[Last/@Abs[n]]},Graphics[{Table[Line[.5+{{-c-1,i},{c,i}}],{i,-r-1,r}],Table[Line[.5+{{i,-r-1},{i,r}}],{i,-c-1,c}],PointSize[.015],Point/@n,Line[n]}]];
Show[walk[With[{k=4,e=80},SeedRandom[1];t=Table[{Cos[Pi x/2],Sin[Pi x/2]},{x,0,k}];
FoldList[Plus,origin,Table[t[[Random[Integer,{1,k}]]],{e}]]]],AspectRatio->Automatic]

Random Walks in 3D

Here, we draw the random walk in 3D using "Accumulate" and an 80 by 3 array of random choices of 1 and -1.

path=Accumulate[RandomChoice[{-1,1},{80,3}]];
Graphics3D[{Line[path],PointSize[Large],Red,Point[path]}]

Self Avoiding Random Walks in 3D

Here, we draw the random walk in 3D, but this time it is a self avoiding random walk.

SelfAvoidwalk[maxL_]:=(Clear[newq];newq[_]:=True;
First/@NestWhileList[{#,Select[Flatten[Outer[Plus,{#},{{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}},1],1],newq]}&[newq[#[[1]]]=False;RandomChoice[#[[2]]]]&,{{0,0,0},{{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}}},#[[2]]=!={}&,1,maxL-1]);
max=100;
SeedRandom[1];
pts=SelfAvoidwalk[max];
Graphics3D[{Thick,Black,Line@pts,Red,Sphere[pts[[1]],.5],Green,Sphere[pts[[-1]],.5]}]

Here, we draw the random walk in 3D as above and then we join the starting and the ending points in attempt to get a knot.

SelfAvoidwalk[maxL_]:=(Clear[newq];newq[_]:=True;
First/@NestWhileList[{#,Select[Flatten[Outer[Plus,{#},{{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}},1],1],newq]}&[newq[#[[1]]]=False;RandomChoice[#[[2]]]]&,{{0,0,0},{{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}}},#[[2]]=!={}&,1,maxL-1]);
max=1022;
SeedRandom[4];
pts=SelfAvoidwalk[max];
Graphics3D[{Thick,Black,Line@pts,Red,Sphere[pts[[1]],.3],Green,Sphere[pts[[-1]],.3],Line[{pts[[1]],pts[[-1]]}]}]