# Langton's ant algorithm using AnglePath

I would like to implement Langton's ant algorithm using AnglePath. I know there are some MMA implementation on the internet but I would like to implement it myself.

Here is definition of algorithm:

• At a white square, turn 90° right, flip the color of the square, move forward one unit
• At a black square, turn 90° left, flip the color of the square, move forward one unit

Here is my try.

ClearAll["Global*"]
mat = ConstantArray[0, {10, 10}];
pos = {5, 5};
s = Table[

seq = Sequence @@ pos;
Which[

mat[[seq]] == 0, {pos = Last@AnglePath[pos, {90 \[Degree]}],
mat[[seq]] = 1},
mat[[seq]] == 1, {pos = Last@AnglePath[pos, {-90 \[Degree]}],
mat[[seq]] = 0}

]; mat , 6];

ArrayPlot[#, Mesh -> All, Frame -> True, FrameTicks -> {True, True},
DataReversed -> True] & /@ s It seems issue is pos; Observe that

AnglePath[{5, 5}, {90 \[Degree], 90 \[Degree], 90 \[Degree]}]


{{5, 5}, {5, 6}, {4, 6}, {4, 5}}

and

AnglePath[#, {90 \[Degree]}] & /@ {{5, 5}, {5, 6}, {4, 6}, {4, 5}}


{{{5, 5}, {5, 6}}, {{5, 6}, {5, 7}}, {{4, 6}, {4, 7}}, {{4, 5}, {4, 6}}}

I need pos=Last@AnglePath in the first iteration and pos=First@AnglePath in the rest of iteration I guess?

Any suggestion?

It seems like you forgot to remember current orientation of the ant:

ClearAll["Global*"]
mat = ConstantArray[0, {100, 100}];
pos = {50, 50, -90 °};
s = Table[
seq = Sequence @@ Most@pos;
Which[
mat[[seq]] == 0, {pos = Flatten@Last@AnglePath[Most@pos, {Last@pos + 90 °}, {"Position", "FrameAngle"}], mat[[seq]] = 1}
, mat[[seq]] == 1, {pos = Flatten@Last@AnglePath[Most@pos, {Last@pos - 90°}, {"Position", "FrameAngle"}], mat[[seq]] = 0}
];
mat
, 11000
];

ArrayPlot[#, Mesh -> All, Frame -> True, FrameTicks -> {True, True},
DataReversed -> True] &[Last@s] • Oh I see, it is beautiful, thanks.. – OkkesDulgerci Nov 1 '19 at 6:09