Skip to main content
Commonmark migration
Source Link

#Mathematica 285

Mathematica 285

#Mathematica 285

Mathematica 285

Source Link
DavidC
  • 25.4k
  • 2
  • 52
  • 105

#Mathematica 285

Golfed

r=RandomChoice;k=False;
s:=r[{{0,1},{-1,0},{1,0},{0,-1}}]
w:=r[{0,1,2,3,4}]
f[{-1,___}]:="";
f[{n_,l_,{h_,d_}}]:=
(Print["H(",h,")\t","D(",d,")"];
m[i_,u_,v_]:=EuclideanDistance[u+i,v]<l;
z=k;While[z==k,t=s;z=m[t,h,d]];
y=h+t;t=w*s;z=k;While[z==k,t=t-Sign@t;z=m[t,d,y]];
dp=d+t;f[{n-1,l,{y, dp}}])

Example

f[{17,7,{{0,0},{0,0}}}]

H({0,0}) D({0,0})
H({1,0}) D({0,0})
H({2,0}) D({0,2})
H({2,-1}) D({0,-1})
H({1,-1}) D({-3,-1})
H({1,0}) D({-3,1})
H({1,1}) D({0,1})
H({1,2}) D({0,2})
H({1,1}) D({0,2})
H({1,0}) D({-2,2})
H({2,0}) D({1,2})
H({2,-1}) D({-2,2})
H({2,0}) D({-2,3})
H({2,1}) D({-2,0})
H({1,1}) D({-2,3})
H({2,1}) D({-2,6})
H({1,1}) D({-3,6})
H({0,1}) D({-4,6})


UnGolfed

There are some comments in the text below. I've also included a printout which makes it possible to follow some of the calculations.

step:=RandomChoice[{{0,1},{-1,0},{1,0},{0,-1}}]
dogWander:=RandomChoice[{0,1,2,3,4}]

f[{-1,___}]:="";

f[{n_,l_,{humanPos_,dogPos_}}]:=
Module[{tempStep,moveOK,hp,hp1,dp,p,test},

(* human imagines step, checks with leash, chooses another step if would choke the dog *)
moveOK[intendedStep_,pos1_,pos2_]:=EuclideanDistance[pos1+intendedStep,pos2]<l;
test=False;While[test==False,tempStep=step;test=moveOK[tempStep,humanPos,dogPos]];
hp=humanPos+tempStep;
Print["humanPos before: ", humanPos,"\t","human step: ",tempStep,"\thumanPos after: ",hp,"\tdistance from dog: ",N@EuclideanDistance[hp,dogPos]];

(*move closer to human if needed *)
tempStep=dogWander*step;
test=False;While[test==False,tempStep=tempStep-Sign[tempStep];test=moveOK[tempStep,dogPos,hp]];
dp=dogPos+tempStep;
Print["dog's intended step: ",tempStep,"\tdogPos before: ",dogPos,"\t","dog actual step: ",tempStep, "\t","dogPos after: ",dp,"\tdistance: ",N@EuclideanDistance[hp,dp],"\n"];
f[{n-1,l,{hp, dp}}]]

Example

f[{17,5,{{0,0},{0,0}}}]

[Part of the printout is shown to give a sense of how the code works. ]

printout