Langton's ant: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(→‎{{header|Processing}}: adding Processing Python mode)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(50 intermediate revisions by 22 users not shown)
Line 28:
 
;Related task:
*   Rosetta Code:   [[Conway%27s_Game_of_Life|Conway's Game of Life]].
*   [[Elementary_cellular_automaton|Elementary cellular automaton]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">T.enum Dir
UP
RIGHT
DOWN
LEFT
 
-V color_WHITE = Char(‘ ’)
-V color_BLACK = Char(‘#’)
 
F invert_color(&grid, x, y)
‘Invert the color of grid at x, y coordinate.’
I grid[y][x] == :color_BLACK
grid[y][x] = :color_WHITE
E
grid[y][x] = :color_BLACK
 
F next_direction(grid, x, y, =direction)
‘Compute next direction according to current position and direction.’
V turn_right = grid[y][x] != :color_BLACK
V direction_index = Int(direction)
I turn_right
direction_index = (direction_index + 1) % 4
E
direction_index = (direction_index + 4 - 1) % 4
V directions = [Dir.UP, Dir.RIGHT, Dir.DOWN, Dir.LEFT]
direction = directions[direction_index]
R direction
 
F next_position(=x, =y, direction)
‘Compute next position according to direction.’
I direction == UP
y--
E I direction == RIGHT
x--
E I direction == DOWN
y++
E I direction == LEFT
x++
R (x, y)
 
F print_grid(grid)
‘Display grid.’
print(80 * ‘#’)
print(grid.map(row -> row.join(‘’)).join("\n"))
 
F ant(width, height, max_nb_steps)
‘Langton's ant.’
V grid = [[:color_WHITE] * width] * height
V x = width I/ 2
V y = height I/ 2
V direction = Dir.UP
 
V i = 0
L i < max_nb_steps & x C 0 .< width & y C 0 .< height
invert_color(&grid, x, y)
direction = next_direction(grid, x, y, direction)
(x, y) = next_position(x, y, direction)
i++
 
print_grid(grid)
 
ant(width' 75, height' 52, max_nb_steps' 12000)</syntaxhighlight>
 
{{out}}
<pre>
################################################################################
 
 
 
 
## ############ ##
# #### # ##
### ## ## #
# # # # # #
## ## # # ### #
### # # # # ## ## ###
# # ### ## #### ## # # # ## ##
# ### ## # ## ### # # ### ###
# # ##### # # #### # ### # # #
### ## # #### ## ## ###### # ### # #
# ### # ## # # ## ## ## # ##### ### ##
# # # ## ### # # # #### # ##
# # ## ## # ## ## # ##
### # # ## ### # ## # ### ## ## #
# ### ## ## ## ### # # ## #### #
### # # # # # #### ## # ## ### # #
# ### # ## # # ### # ### ## # # ##
### # # ## # ## ## ##### #### #### ## #
# ### # # # # ### # # ## ## # # # # #
### # ## ### ## # ## #### #### # #
# ### # # # ## ########### # #### # # #
### # ## # #### ## ######### # ## # ##
# ### # # ## # ## ## ## ### ### # # ## #### #
### # ## # # ###### ## # ## # # ### ### ## #
# ### # # # ##### # ##### # # ## # ## #
### # ## # # ## ##### ## # # # # ## # # #
# ### # # # # #### # ##### ## ########## ##
### # ## # ## ## # # #### # ## #### ##
# ### # # ##### # ## ## # # # # # # # #
### # ## ## ## # # # ## ## # # ## # ## ##
# ### # # # # # ######## # # ## #### #
### # ## # # # ## ## # # ## #
## # # # # # # ## ## ## ####
## # ## ## # ## ## # # ###
# # # # # ## #### #### ### ####
#### ## ## #### ## # ## # # #
# ## # ## ## ## ### ## #####
#### # ## # ####
## ## ## ##
##
# ## #### #
# # ### ###
# ## # # #
## ##
##
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE DIRN="0"
DEFINE DIRE="1"
DEFINE DIRS="2"
DEFINE DIRW="3"
DEFINE BLACK="1"
DEFINE WHITE="2"
DEFINE MAXX="159"
DEFINE MAXY="95"
 
BYTE FUNC TurnLeft(BYTE dir)
IF dir=DIRN THEN
RETURN (DIRW)
FI
RETURN (dir-1)
 
BYTE FUNC TurnRight(BYTE dir)
IF dir=DIRW THEN
RETURN (DIRN)
FI
RETURN (dir+1)
 
PROC DrawAnt(INT x,y)
BYTE c,dir
 
dir=DIRN
DO
c=Locate(x,y)
IF c=BLACK THEN
Color=WHITE
Plot(x,y)
dir=TurnLeft(dir)
ELSE
Color=BLACK
Plot(x,y)
dir=TurnRight(dir)
FI
IF dir=DIRN THEN
y==-1
IF y<0 THEN EXIT FI
ELSEIF dir=DIRE THEN
x==+1
IF X>MAXX THEN EXIT FI
ELSEIF dir=DIRS THEN
y==+1
IF Y>MAXY THEN EXIT FI
ELSE
x==-1
IF x<0 THEN EXIT FI
FI
OD
RETURN
 
PROC Main()
BYTE CH=$02FC
BYTE y
 
Graphics(7+16)
SetColor(0,0,2)
SetColor(1,0,12)
Color=2
FOR y=0 TO MAXY
DO
Plot(0,y) DrawTo(MAXX,y)
OD
 
DrawAnt(80,48)
 
DO UNTIL CH#$FF OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Langton's_ant.png Screenshot from Atari 8-bit computer]
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Langtons_Ant is
Line 88 ⟶ 285:
Ada.Text_IO.Put_Line("# Iteration:" & Integer'Image(Iteration));
end Langtons_Ant;
</syntaxhighlight>
</lang>
Ouptut (to save space, I have removed the all-blank lines):
<pre style="height:30ex;overflow:scroll"> ## ############ ##
Line 146 ⟶ 343:
=={{header|Aime}}==
[[File:ant_phpoFTAAk.png|100px|Output png]]
<langsyntaxhighlight lang="aime">void
ant(integer x, y, d, list map)
{
Line 178 ⟶ 375:
 
0;
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
# size of board for Langton's ant #
INT max board = 100;
Line 247 ⟶ 444:
print( ( board[ r, min col : max col ], newline ) )
OD
END</langsyntaxhighlight>
{{out}}
<pre>
Line 303 ⟶ 500:
##
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">
⍝ initialize a Langton's Ant setup with a grid of size left x right (square by default)
langton ← {
⍝ If rows not specified, set equal to columns
⍺ ← ⍵
 
⍝ 0=white, 1=black. Start with all white
grid ← ⍺ ⍵ ⍴ 0
 
⍝ Start the ant in the middle
ant ← 2 ÷⍨ ⍺ ⍵
 
⍝ Aimed in a random direction
dir ← ?4
 
⍝ return everything in a tuple
grid ant dir
}
 
⍝ iterate one step: takes and returns state as created by langton function
step ← {
grid ant dir ← ⍵
 
⍝ Turn left or right based on grid cell
dir ← 1 + 4|dir+2×grid[⊂ant]
 
⍝ Toggle cell color
grid[⊂ant] ← 1 - grid[⊂ant]
 
⍝ Advance along dir. Since coordinates are matrix order (row,col),
⍝ up is -1 0, right is 0 1, down is 1 0, and left is 0 -1
ant +← (4 2 ⍴ ¯1 0, 0 1, 1 0, 0 ¯1)[dir;]
 
grid ant dir
}
 
⍝ to watch it run, open the variable pic in the monitor before executing this step
{} { state ∘← ⍵ ⋄ pic ∘← '.⌺'[1+⊃1⌷⍵] ⋄ _←⎕dl ÷200 ⋄ step ⍵} ⍣≡ langton 100</syntaxhighlight>
 
{{Out}}
The final contents of <tt>pic</tt> (eliding trailing blank lines)
<pre>.......................⌺⌺.⌺.⌺.......................................................................
......................⌺.⌺⌺⌺.⌺⌺......................................................................
.....................⌺⌺⌺⌺...⌺.⌺.....................................................................
.....................⌺⌺⌺⌺⌺.⌺..⌺⌺....................................................................
......................⌺...⌺⌺.⌺⌺.⌺...................................................................
.......................⌺⌺⌺...⌺..⌺⌺..................................................................
........................⌺...⌺⌺.⌺⌺.⌺.................................................................
.........................⌺⌺⌺...⌺..⌺⌺................................................................
..........................⌺...⌺⌺.⌺⌺.⌺...............................................................
...........................⌺⌺⌺...⌺..⌺⌺..............................................................
............................⌺...⌺⌺.⌺⌺.⌺.............................................................
.............................⌺⌺⌺...⌺..⌺⌺............................................................
..............................⌺...⌺⌺.⌺⌺.⌺...........................................................
...............................⌺⌺⌺...⌺..⌺⌺..........................................................
................................⌺...⌺⌺.⌺⌺.⌺.........................................................
.................................⌺⌺⌺...⌺..⌺⌺........................................................
..................................⌺...⌺⌺.⌺⌺.⌺.......................................................
...................................⌺⌺⌺...⌺..⌺⌺......................................................
....................................⌺...⌺⌺.⌺⌺.⌺.....................................................
.....................................⌺⌺⌺...⌺..⌺⌺....................................................
......................................⌺...⌺⌺.⌺⌺.⌺...................................................
.......................................⌺⌺⌺...⌺..⌺⌺..................................................
........................................⌺...⌺⌺.⌺⌺.⌺.................................................
.........................................⌺⌺⌺...⌺..⌺⌺................................................
..........................................⌺...⌺⌺.⌺⌺.⌺...............................................
...........................................⌺⌺⌺...⌺..⌺⌺..............................................
............................................⌺...⌺⌺.⌺⌺.⌺.............................................
.............................................⌺⌺⌺...⌺..⌺⌺............................................
..............................................⌺...⌺⌺.⌺⌺.⌺...........................................
...............................................⌺⌺⌺...⌺..⌺⌺..........................................
................................................⌺...⌺⌺.⌺⌺.⌺..⌺⌺.....................................
.................................................⌺⌺⌺...⌺..⌺⌺..⌺⌺....................................
..................................................⌺...⌺⌺.⌺⌺..⌺⌺...⌺.................................
............................................⌺⌺⌺⌺...⌺⌺⌺...⌺...⌺..⌺⌺⌺.................................
...........................................⌺....⌺...⌺...⌺⌺.⌺⌺⌺⌺...⌺.................................
..........................................⌺⌺⌺....⌺...⌺.⌺......⌺.⌺⌺.⌺................................
..........................................⌺⌺⌺....⌺.⌺⌺.....⌺.⌺⌺..⌺.⌺⌺................................
...........................................⌺....⌺...⌺⌺.⌺.⌺.....⌺⌺...................................
...........................................⌺.⌺......⌺.⌺⌺⌺⌺⌺..⌺...⌺..................................
..........................................⌺...⌺⌺⌺⌺⌺..........⌺⌺.⌺⌺⌺⌺⌺⌺..............................
..........................................⌺⌺⌺..⌺⌺..⌺.⌺⌺.⌺.⌺.⌺...⌺⌺.⌺.⌺⌺.............................
........................................⌺⌺..⌺.⌺⌺⌺⌺⌺⌺⌺.⌺...⌺..⌺⌺⌺....⌺⌺.⌺............................
.......................................⌺..⌺..⌺⌺⌺⌺⌺⌺.⌺⌺...⌺..⌺.⌺⌺...⌺...⌺............................
......................................⌺....⌺.⌺.⌺⌺.⌺..⌺⌺⌺⌺⌺⌺.⌺⌺⌺⌺⌺⌺⌺...⌺.............................
......................................⌺.⌺⌺⌺⌺.⌺⌺.⌺.⌺⌺⌺⌺....⌺⌺..⌺⌺.⌺.⌺⌺.⌺.............................
.......................................⌺....⌺⌺⌺⌺...⌺..⌺.⌺⌺⌺⌺⌺⌺.⌺⌺....⌺⌺⌺............................
..........................................⌺...⌺.⌺⌺.⌺.⌺⌺⌺.⌺..⌺⌺..⌺⌺...⌺⌺⌺............................
.............................................⌺⌺⌺⌺⌺⌺⌺....⌺..⌺⌺.⌺⌺.⌺.....⌺............................
.....................................⌺⌺⌺⌺..⌺⌺.⌺⌺..⌺⌺⌺⌺.⌺⌺.⌺⌺.⌺⌺..⌺.....⌺............................
....................................⌺....⌺.⌺...⌺⌺⌺.⌺⌺.⌺⌺⌺....⌺.⌺⌺⌺⌺....⌺............................
...................................⌺⌺⌺.......⌺⌺⌺.⌺.⌺.⌺⌺⌺⌺⌺....⌺.⌺......⌺............................
...................................⌺.⌺...⌺⌺⌺.⌺⌺⌺⌺.⌺⌺.⌺...⌺⌺.⌺⌺⌺.⌺⌺.....⌺............................
.........................................⌺⌺.⌺⌺..⌺⌺⌺⌺....⌺⌺⌺⌺.⌺.⌺.⌺.....⌺............................
....................................⌺....⌺..⌺⌺...⌺⌺⌺..⌺⌺⌺.....⌺⌺⌺......⌺............................
....................................⌺⌺...⌺⌺.⌺⌺⌺.⌺⌺⌺⌺..⌺......⌺⌺⌺...⌺⌺..⌺............................
....................................⌺⌺.⌺.⌺⌺⌺⌺.....⌺...⌺..⌺.⌺⌺.⌺⌺⌺.⌺⌺...⌺............................
...................................⌺⌺⌺⌺.⌺⌺...⌺⌺.⌺⌺⌺⌺..⌺.⌺..⌺..⌺..⌺⌺⌺...⌺............................
...................................⌺.⌺⌺.⌺⌺⌺..⌺.⌺.⌺⌺.⌺.⌺.....⌺.⌺.....⌺.⌺.............................
.......................................⌺.⌺..⌺....⌺⌺.⌺⌺..⌺.⌺..⌺⌺⌺.⌺⌺.................................
.......................................⌺⌺.⌺....⌺..⌺⌺⌺⌺⌺.⌺....⌺....⌺..⌺.⌺............................
......................................⌺.⌺⌺.⌺..⌺....⌺⌺.⌺⌺.⌺..⌺⌺⌺......⌺⌺⌺............................
....................................⌺.⌺...⌺..⌺..⌺..⌺..⌺⌺⌺...⌺⌺..⌺⌺....⌺.............................
...................................⌺⌺⌺.⌺.⌺⌺⌺⌺⌺.⌺⌺⌺⌺⌺⌺.⌺⌺⌺.⌺⌺⌺⌺⌺⌺⌺.⌺.⌺⌺..............................
...................................⌺.⌺.⌺....⌺⌺⌺⌺⌺...⌺⌺..⌺⌺⌺⌺⌺.⌺⌺⌺⌺⌺.................................
.....................................⌺..⌺⌺...⌺......⌺..⌺.⌺⌺..⌺⌺⌺.⌺⌺⌺................................
..................................⌺⌺⌺⌺...⌺⌺⌺⌺⌺.⌺⌺⌺⌺⌺⌺⌺⌺⌺...⌺.⌺......................................
.............................⌺⌺....⌺..⌺.....⌺⌺⌺.⌺.⌺...⌺.⌺⌺⌺..⌺⌺⌺....................................
............................⌺..⌺..⌺⌺⌺⌺.⌺⌺...⌺⌺⌺.⌺⌺...⌺⌺⌺.⌺⌺.....⌺⌺..................................
...........................⌺⌺⌺....⌺.⌺⌺.⌺.⌺⌺⌺⌺⌺...⌺....⌺..⌺..⌺⌺.⌺⌺⌺..................................
...........................⌺.⌺⌺⌺⌺⌺.⌺.⌺...⌺⌺..⌺⌺.....⌺....⌺...⌺..⌺...................................
...............................⌺⌺⌺⌺⌺⌺.⌺⌺⌺⌺..⌺⌺.⌺...⌺..⌺⌺..⌺.⌺.⌺⌺....................................
.............................⌺⌺......⌺.⌺⌺⌺.⌺⌺..⌺⌺⌺⌺...⌺...⌺⌺⌺.......................................
..............................⌺..⌺.⌺⌺⌺⌺⌺..⌺...⌺.⌺⌺...⌺..⌺..⌺........................................
..............................⌺⌺.⌺⌺⌺.⌺⌺⌺⌺⌺⌺⌺.....⌺.....⌺.⌺⌺.........................................
.............................⌺.⌺..⌺⌺.⌺⌺......⌺...⌺⌺....⌺............................................
............................⌺..⌺.⌺⌺⌺⌺........⌺⌺⌺..⌺⌺..⌺.............................................
............................⌺.⌺⌺.⌺⌺⌺............⌺⌺..⌺⌺..............................................
.............................⌺⌺.....................................................................
..............................⌺⌺....................................................................</pre>
 
=={{header|Applesoft BASIC}}==
{{trans|BBC BASIC}}
<syntaxhighlight lang="gwbasic"> 0 IF T THEN FOR Q = 0 TO T STEP 0: XDRAW T AT X * S,H - Y * S:D = FN M(D + D( PEEK (234)) + F):X = X + X(D):Y = Y + Y(D):Q = X > M OR X < 0 OR Y > M OR Y < 0: NEXT Q: END : DATA 100,50,50,3,220,1,4,-1,1,1,1,-1,-1
1 HGR : SCALE= 1: ROT= 0
2 LET S$ = CHR$ (1) + CHR$ (0) + CHR$ (4) + CHR$ (0) + "5'" + CHR$ (0)
3 POKE 236, PEEK (131): POKE 237, PEEK (132)
4 LET S = PEEK (236) + PEEK (237) * 256 + 1
5 POKE 232, PEEK (S)
6 POKE 233, PEEK (S + 1)
7 READ M,X,Y,S,H,T,F,D(0),D(4),Y(0),X(1),Y(2),X(3)
8 DEF FN M(N) = N - INT (N / F) * F
9 GOTO</syntaxhighlight>
 
=={{header|AutoHotkey}}==
ahk forum: [http://ahkscript.org/boards/viewtopic.php?f=17&t=1363 discussion]
{{works with|AutoHotkey 1.1}} (Fixed by just me)
<langsyntaxhighlight AutoHotkeylang="autohotkey">#NoEnv
SetBatchLines, -1
; Directions
Line 362 ⟶ 695:
HBM := DllCall("User32.dll\CopyImage", "Ptr", HBM, "UInt", 0, "Int", 0, "Int", 0, "Int", 8, "UPtr")
return DllCall("User32.dll\CopyImage", "Ptr", HBM, "UInt", 0, "Int", BMW, "Int", BMH, "UInt", 0x200C, "UPtr")
} ; http://ahkscript.org/boards/viewtopic.php?f=6&t=3203</langsyntaxhighlight>
 
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
<lang AutoIt>
Global $iCountMax = 100000
Global $aFields[100][100][2]
Line 442 ⟶ 775:
Return 1
EndFunc ;==>_SetAnt
</syntaxhighlight>
</lang>
[http://www.imgbox.de/users/BugFix/langtons_ant.png To see the GUI output, click here.]
--[[User:BugFix|BugFix]] ([[User talk:BugFix|talk]]) 14:48, 16 November 2013 (UTC)
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">
# usage: awk -v debug=0 -f langton.awk
 
Line 541 ⟶ 874:
}
END { print("END.") }
</syntaxhighlight>
</lang>
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbc basic">
<lang BBC BASIC>
REM Implementation of Langton's ant for Rosetta Code
fieldsize%=100
Line 566 ⟶ 899:
UNTIL x%>fieldsize% OR x%<0 OR y%>fieldsize% OR y%<0
END
</syntaxhighlight>
</lang>
 
=={{header|bc}}==
The output function <code>o</code> prints the resulting image (as a [[wp:Netpbm_format|PBM image]]) to <code>stdout</code>. One can either store it into a file or pipe it through an image viewer (e.g. <code>bc langton.bc | display</code>).
 
<langsyntaxhighlight lang="bc">define o() {
auto i, j
Line 620 ⟶ 953:
 
l(100, 100, 50, 50)
quit</langsyntaxhighlight>
 
=={{header|Befunge}}==
 
<langsyntaxhighlight lang="befunge">"22222 -"*>>>1-:0\:"P"%\v>\7%1g48*-/2%3*48*+,1+:20g`!v1g01+55p03:_$$$>@
!"$(0@`vp00_^#!:p+7/"P"<<^g+7/*5"p"\%"P"/7::+g03*"d":_$,1+>:40g`!^1g03<
_::10g\v>00g+4%:00p::3\`\1-*50g+50p:2\-\0`*+::0\`\"c"`+50g:0\`\"c"`++#^
-*84g1<v^+1*2g09pg08g07-*g06-1*2p09:%2/g06:gp08:+7/*5"p"\p07:%"P"/7:p06
0p+:7%^>>-:0`!*+10p::20g\-:0`*+20p:"d"*50g::30g\-:0`!*+30p::40g\-:0`*+4</langsyntaxhighlight>
 
{{out}}
Line 683 ⟶ 1,016:
####
##</pre>
 
=={{header|BQN}}==
<code>Ant</code> is the main function, which runs the ant simulation given a starting point, direction and grid of zeros.
 
<code>Fmt</code> then formats into hashes and spaces.
 
<code>_while_</code> is an idiom from [https://mlochbaum.github.io/bqncrate/ BQNcrate] which helps with conditional looping.
 
<syntaxhighlight lang="bqn">Rot ← ¬⊸{-⌾(𝕨⊸⊑)⌽𝕩}
Fmt ← ⊏⟜" #"
_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
 
Ant ← 2⊑{ # Generator Block
p‿d‿g:
r ← d Rot˜ p⊑g
p + r
r
¬⌾(p⊸⊑)g
} _while_ { # Condition Block
p‿d‿g:
∧´(p≥0‿0)∧p<≢g
}
 
•Show Fmt Ant ⟨50‿50, 0‿1, 100‿100⥊0⟩</syntaxhighlight>
 
[https://mlochbaum.github.io/BQN/try.html#code=Um90IOKGkCDCrOKKuHst4oy+KPCdlajiirjiipEp4oy98J2VqX0KRm10IOKGkCDiio/in5wiICMiCl93aGlsZV8g4oaQIHvwnZS94o2f8J2UvuKImPCdlL1f8J2Vo1/wnZS+4oiY8J2UveKNn/CdlL7wnZWpfQoKQW50IOKGkCAy4oqReyAjIEdlbmVyYXRvciBCbG9jawogIHDigL9k4oC/ZzoKICByIOKGkCBkIFJvdMucIHDiipFnCiAg4p+oCiAgICBwICsgcgogICAgcgogICAgwqzijL4ocOKKuOKKkSlnCiAg4p+pCn0gX3doaWxlXyB7ICAgIyBDb25kaXRpb24gQmxvY2sKICBw4oC/ZOKAv2c6CiAg4oinwrQocOKJpTDigL8wKeKIp3A84omiZwp9CgrigKJTaG93IEZtdCBBbnQg4p+oNTDigL81MCwgMOKAvzEsIDEwMOKAvzEwMOKlijDin6k=&norun Try It!] (Running will take some time due to JS, ≈40 secs on my machine)
 
=={{header|C}}==
Requires ANSI terminal.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 760 ⟶ 1,121:
walk();
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
namespace LangtonAnt
Line 856 ⟶ 1,217:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 945 ⟶ 1,306:
 
If you want to see it running infinitely, set the const bool INFINIT_RUN = true
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <string>
Line 1,244 ⟶ 1,605:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
 
=={{header|Chapel}}==
<langsyntaxhighlight lang="chapel">
config const gridHeight: int = 100;
config const gridWidth: int = 100;
Line 1,316 ⟶ 1,677:
image.writeImage( "output.png" );
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
In keeping with the spirit of Clojure, this program eschews mutable state entirely. Instead, all computation occurs within a single recursive loop whose "variables" are "adjusted" at each iteration, a natural fit for this particular execution model.
<langsyntaxhighlight Clojurelang="clojure">(let [bounds (set (range 100))
xs [1 0 -1 0] ys [0 -1 0 1]]
(loop [dir 0 x 50 y 50
Line 1,333 ⟶ 1,694:
(apply str
(map #(if (grid [% col]) \# \.)
(range 100))))))))</langsyntaxhighlight>
 
=={{header|COBOL}}==
The following program displays the simulation in the console, and a very small font size (~4pt) will be needed to fit it into the window.
{{works with|OpenCOBOL}}
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. langtons-ant.
 
Line 1,428 ⟶ 1,789:
WITH BACKGROUND-COLOR White-Background
END-PERFORM
.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
class Ant
constructor: (@world) ->
Line 1,511 ⟶ 1,872:
console.log "Ant is at #{ant.location}, direction #{ant.direction}"
world.draw()
</syntaxhighlight>
</lang>
 
output
 
<syntaxhighlight lang="text">
> coffee langstons_ant.coffee
Ant is at -24,46, direction W
Line 1,596 ⟶ 1,957:
_____##_________________________________________
______##________________________________________
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defmacro toggle (gv) `(setf ,gv (not ,gv)))
 
(defun langtons-ant (width height start-x start-y start-dir)
Line 1,630 ⟶ 1,991:
 
(setf *random-state* (make-random-state t))
(show-grid (langtons-ant 100 100 (+ 45 (random 10)) (+ 45 (random 10)) (random 4)))</langsyntaxhighlight>
 
=={{header|D}}==
===Textual Version===
<langsyntaxhighlight lang="d">void main() @safe {
import std.stdio, std.traits;
 
Line 1,659 ⟶ 2,020:
 
writefln("%(%-(%c%)\n%)", M);
}</langsyntaxhighlight>
{{out}}
<pre>...........................................................................
Line 1,716 ⟶ 2,077:
===Image Version===
This similar version requires the module from the Grayscale Image Task to generate and save a PGM image.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.traits, grayscale_image;
 
void main() {
Line 1,740 ⟶ 2,101:
 
M.savePGM("langton_ant.pgm");
}</langsyntaxhighlight>
 
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang="dyalect">constlet xInc = [0, 1, -1, 0]
constlet yInc = [-1, 0, 0, 1]
constlet north = 0
constlet east = 1
constlet west = 2
constlet south = 3
 
constlet leftTurns = [ west, north, south, east ]
constlet rightTurns = [ east, south, north, west ]
 
func move(ant) {
ant.position.x += xInc[ant.direction]
ant.position.y += yInc[ant.direction]
}
 
func Array.stepStep(ant) {
var ptCur = (var x: ant.position.x + ant.origin.x, var y: ant.position.y + ant.origin.y)
var leftTurn = this[ptCur.x][ptCur.y]
ant.direction =
Line 1,778 ⟶ 2,139:
ant.position
}
 
func newAnt(width, height) {
(
var position: (var x: 0, var y: 0),
var origin: (x: width / 2, y: height / 2),
var outOfBounds: false,
var isBlack: [],
var direction: east,
var width: width,
var height: height
)
}
 
func run() {
constlet w = 100
constlet h = 100
constlet blacks = Array.emptyEmpty(w, () => Array.emptyEmpty(h, false))
constlet ant = newAnt(w, h)
 
while !ant.outOfBounds {
blacks.stepStep(ant)
}
 
var iRow = 0;
 
while iRow < w {
var iCol = 0;
Line 1,818 ⟶ 2,179:
}
}
 
run()</langsyntaxhighlight>
 
{{out}}
Line 1,908 ⟶ 2,269:
=={{header|EasyLang}}==
 
[https://easylang.dev/show/#cod=bZHLDoIwEEX3/Yq7VAlNa0wMifgjhIXhEUiUmopA/94ZKILBJn3k9M70zvReNCiTFFopHHgVT2syvCrTQ0IKAKWxcIih0BpEESNPhw2lUZeU0E3JEJAmgE5JqBcJjYfpCrpzP9AWWQu9Vkqx2qWQkzv7bjgWeW1nk/mQ8CMJ+dE0Q410xM7jUPubEfdVfefnr+z/1uR0vIx++ewW7CbsTXSUaVva3I+/NSNE5wVsNsaOtwBH0nZ76kKOE4u9hgJjLoVEc143IvdF3ASu/6xwUlCCf0p8AA== Run it]
[https://easylang.online/ide/?run=len%20f%5B%5D%20100%2A100%0Afunc%20show%20.%20.%0Afor%20y%20range%20100%0Afor%20x%20range%20100%0Aif%20f%5By%2A100%2Bx%5D%3D1%0Amove%20x%20y%0Arect%201%201%0A.%0A.%0A.%0A.%0Afunc%20run%20x%20y%20dir%20.%20.%0Adx%5B%5D%3D%5B%200%201%200%20-1%20%5D%0Ady%5B%5D%3D%5B%20-1%200%201%200%20%5D%0Awhile%20x%20%3E%3D%200%20and%20x%20%3C%20100%20and%20y%20%3E%3D%200%20and%20y%20%3C%20100%0Av%3Df%5By%2A100%2Bx%5D%0Af%5By%2A100%2Bx%5D%3D1%20-%20v%0Adir%3D%28dir%2B1%2B2%2Av%29%20mod%204%0Ax%2B%3Ddx%5Bdir%5D%0Ay%2B%3Ddy%5Bdir%5D%0A.%0A.%0Acall%20run%2070%2040%200%0Acall%20show Run it]
 
<syntaxhighlight lang="text">
<lang>len f[] 100 * 100
len f[] 100 * 100
func show . .
proc show . .
for y range 100
for xy = 0 rangeto 10099
iffor f[yx *= 1000 + x] =to 199
move xif f[y * 100 + x + 1] = 1
rect 1 1 move x y
rect 1 1
.
.
.
.
.
funcproc run x y dir . .
dx[] = [ 0 1 0 -1 ]
dy[] = [ -1 0 1 0 ]
while x >= 0 and x < 100 and y >= 0 and y < 100
v = f[y * 100 + x + 1]
f[y * 100 + x + 1] = 1 - v
dir = (dir + 1 + 2 * v) mod 4 + 1
x += dx[dir]
y += dy[dir]
.
.
call run 70 40 0
call show</lang>
</syntaxhighlight>
 
=={{header|EchoLisp}}==
We implement multi-colored ants, as depicted in the article. An ant is described using L(eft)R(ight) patterns. LR is the basic black and white ant, other are RRLLLRRL or RRLLLRLLLRRR. See results for s [http://www.echolalie.org/echolisp/images/ant-1.png black-and-white] or [http://www.echolalie.org/echolisp/images/ant-2.png colored] ants.
<langsyntaxhighlight lang="scheme">
(lib 'plot)
(lib 'types)
Line 1,997 ⟶ 2,360:
 
(ant) ;; run
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
Line 2,003 ⟶ 2,366:
A straightforward implementation (assumes that we start with ant looking forward):
 
<langsyntaxhighlight lang="ela">open list core generic
type Field = Field a
Line 2,053 ⟶ 2,416:
left Bwd = Rgt
left Rgt = Fwd
left Fwd = Lft</langsyntaxhighlight>
 
This implementation is pure (doesn't produce side effects).
Line 2,059 ⟶ 2,422:
Testing:
 
<langsyntaxhighlight lang="ela">showPath <| move 100 50 50</langsyntaxhighlight>
 
Output (empty lines are skipped to save space):
Line 2,119 ⟶ 2,482:
{{works with|Elixir|1.1+}}
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Langtons do
def ant(sizex, sizey) do
{px, py} = {div(sizex,2), div(sizey,2)} # start position
Line 2,145 ⟶ 2,508:
end
 
Langtons.ant(100, 100)</langsyntaxhighlight>
 
{{out}}
Line 2,254 ⟶ 2,617:
 
=={{header|Elm}}==
<langsyntaxhighlight lang="elm">import Maybe as M
import Matrix
import Time exposing (Time, every, second)
Line 2,385 ⟶ 2,748:
, update = update
, subscriptions = subscriptions
}</langsyntaxhighlight>
 
Link to live demo: https://dc25.github.io/langtonsAntElm/
Line 2,391 ⟶ 2,754:
=={{header|Erlang}}==
Over-engineered sine I have summer vacation. Ex: Display function only display lines with black cells.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( langtons_ant ).
 
Line 2,504 ⟶ 2,867:
plane_create( Controller, Max_x, Max_y ) -> [{plane_create_cell(Controller, Max_x, Max_y, {X, Y}), {X,Y}} || X <- lists:seq(1, Max_x), Y<- lists:seq(1, Max_y)].
plane_create_cell( Controller, Max_x, Max_y, Position ) -> erlang:spawn_link( fun() -> loop( #state{controller=Controller, max_x=Max_x, max_y=Max_y, position=Position} ) end ).
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,591 ⟶ 2,954:
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.3, 4.0.0 RC1 and later}}
<langsyntaxhighlight lang="euphoria">include std\console.e
include std\graphics.e
 
Line 2,655 ⟶ 3,018:
 
printf(1,"\n%d Iterations\n",iterations)
any_key()--wait for keypress, put default message 'press any key..'</langsyntaxhighlight>[[File:LangtonsAnt_Euphoria_SDL.png|right|thumb|SDL output]]
Code needed to run SDL example with Mark Akita's SDL_gfx_Test1.exw (as template) included with his SDL_gfx package from rapideuphoria.com's archive -
In initialization section :<langsyntaxhighlight lang="euphoria">
sequence grid = repeat(repeat(1,100),100) --fill 100 by 100 grid with white (1)
sequence antData = {48, 53, 360} --x coordinate, y coordinate, facing angle</langsyntaxhighlight>
In main() , after keystate=SDL_GetKeyState(NULL) , you can adapt the program above to draw the ant's step each frame.
Use dummy=pixelColor(surface,x+20,y+12,#000000FF) (for example) to replace the text output.
Just before the close of the while loop, use dummy=pixelColor(surface,antData[1]+20,antData[2]+12,#FF0000FF) for the ant
and SDL_UpdateRect(surface,0,0,0,0) to display the graphic.
 
 
 
 
=={{header|F Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// Langton's ant F# https://rosettacode.org/wiki/Langton%27s_ant
 
// A list of cells which are black is maintained and then printed out at the end
 
type Cell = { X : int; Y : int }
type Direction = | North | South | East| West // direction the ant is facing
 
let withinBounds (dim:int) (cell: Cell) = // ant's cell within dimensions ?
cell.X < dim && cell.Y < dim && cell.X >= 0 && cell.Y >= 0
 
let rotateLeft (currentDirection: Direction) =
match currentDirection with
| North -> West | South -> East | East -> North | West -> South
 
let rotateRight (currentDirection: Direction ) =
match currentDirection with
| North -> East | South -> West | East -> South | West -> North
 
let nextCell (dir:Direction) (cell: Cell) = // compute next cell based on the direction
match dir with
| North -> {cell with Y = cell.Y + 1 }
| South -> {cell with Y = cell.Y - 1 }
| East -> {cell with X = cell.X + 1 }
| West -> {cell with X = cell.X - 1 }
 
let isBlackCell (blackCells: Cell list) (cell:Cell) =
blackCells |> List.exists ( fun c -> c = cell)
 
let toggleCellColor (blackCells: Cell list) (cell: Cell) =
if cell |> isBlackCell blackCells
then blackCells |> List.where( fun c -> c <> cell) // remove the cell from list of black cells
else cell::blackCells // add the cell to the list of black cells
 
let moveToCell (blackCells: Cell list) (currentDir : Direction) (cell: Cell) =
let ndir = if cell |> isBlackCell blackCells // next step direction is computed
then rotateLeft currentDir
else rotateRight currentDir
let nlst = cell |> toggleCellColor blackCells // next step updated list of black cells is computed
let ncell = cell |> nextCell ndir // next step cell is computedd
(nlst, ndir, ncell) // return next step list of black cells, direction it will enter the cell, new cell
let rec doStep (dim:int) (blackCells: Cell list) (dir : Direction) (cell: Cell) =
let (nlst, ndir, ncell) = moveToCell blackCells dir cell
if withinBounds dim ncell // check if the next step is within bounds
then doStep dim nlst ndir ncell // recursive call to next step
else nlst, ndir, ncell
 
[<EntryPoint>]
let main _ =
let dim = 100
let (blacklist, _, _) = doStep dim [] North { X = dim/2 ; Y = dim/2 } // start with empty blacklist, facing north in the center
 
// print out by row, 0th row is at the bottom
seq { for row in [dim-1..-1..0] do for col in [0..dim-1] -> (col,row) }
|> Seq.iter (fun (row,col) -> if {X = row; Y = col } |> isBlackCell blacklist
then printf "#" else printf " "
if row = (dim - 1 )
then printf "\n" else ()
)
0
 
</syntaxhighlight>
 
<pre>
## ############ ##
# #### # ##
### ## ## #
# # # # # #
## ## # # ### #
### # # # # ## ## ###
# # ### ## #### ## # # # ## ##
# ### ## # ## ### # # ### ###
# # ##### # # #### # ### # # #
### ## # #### ## ## ###### # ### # #
# ### # ## # # ## ## ## # ##### ### ##
# # # ## ### # # # #### # ##
# # ## ## # ## ## # ##
### # # ## ### # ## # ### ## ## #
# ### ## ## ## ### # # ## #### #
### # # # # # #### ## # ## ### # #
# ### # ## # # ### # ### ## # # ##
### # # ## # ## ## ##### #### #### ## #
# ### # # # # ### # # ## ## # # # # #
### # ## ### ## # ## #### #### # #
# ### # # # ## ########### # #### # # #
### # ## # #### ## ######### # ## # ##
# ### # # ## # ## ## ## ### ### # # ## #### #
### # ## # # ###### ## # ## # # ### ### ## #
# ### # # # ##### # ##### # # ## # ## #
### # ## # # ## ##### ## # # # # ## # # #
# ### # # # # #### # ##### ## ########## ##
### # ## # ## ## # # #### # ## #### ##
# ### # # ##### # ## ## # # # # # # # #
### # ## ## ## # # # ## ## # # ## # ## ##
# ### # # # # # ######## # # ## #### #
### # ## # # # ## ## # # ## #
# ### # # # # # # ## ## ## ####
### # ## ## # ## ## # # ###
# ### # # # ## #### #### ### ####
### # ## ## #### ## # ## # # #
# ### # # ## ## ## ### ## #####
### # ## # ## # ####
# ### # # ## ## ##
### # ## ##
# ### # # # ## #### #
### # ## # # ### ###
# ### # # # ## # # #
### # ## ## ##
# ### # # ##
### # ##
# # # # #
#### ##
# ## #
####
##
 
</pre>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class World
{
Line 2,798 ⟶ 3,285:
}
}
</syntaxhighlight>
</lang>
 
Output (snipping the blank lines):
Line 2,859 ⟶ 3,346:
{{works with|GNU Forth|0.7.0}}
All array manipulations were taken from Rosetta Code examples.
<langsyntaxhighlight lang="forth">
1 0 0 0 \ pushes orientation of the ant to the stack.
 
Line 2,926 ⟶ 3,413:
: langton.ant run.ant draw.grid ; \ launches the ant, outputs the result
 
</langsyntaxhighlight>
{{out}}
<pre style="height:60ex;overflow:scroll">
Line 3,013 ⟶ 3,500:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Langtons_Ant
implicit none
 
Line 3,060 ⟶ 3,547:
write(*,*)
end do
end program</langsyntaxhighlight>
{{out}} (Cropped to save space)
<pre style="height:60ex;overflow:scroll">
Line 3,120 ⟶ 3,607:
 
===But, if one remembers complex numbers===
<syntaxhighlight lang="fortran">
<lang Fortran>
PROGRAM LANGTONSANT
C Langton's ant wanders across an initially all-white board, stepping one cell at a go.
Line 3,167 ⟶ 3,654:
Completed.
END
</syntaxhighlight>
</lang>
 
Output is the same, except for orientation. Here I have stuck to (x,y) Cartesian orientation rather than lines (y) increasing downwards. Just for fun, + signs mark cells that have been trampled and then cleaned. But not to pure white... Notice that some interior cells have never been trampled.
Line 3,256 ⟶ 3,743:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 16-10-2016
' compile with: fbc -s gui
 
Line 3,320 ⟶ 3,807:
'Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
 
=={{header|Furor}}==
<syntaxhighlight lang="furor">
###sysinclude X.uh
$ff0000 sto szin1
$ffffff sto szin2
2 sto pausetime
maxypixel 100 - sto YRES
maxxpixel sto XRES
zero ant
// Az ant iránykódjai:
// 0 : fel
// 1 : le
// 2 : jobbra
// 3 : balra
@XRES 2 / sto antx // Az ant kezdeti koordinátái
@YRES 2 / sto anty
myscreen "Furor monitor" @YRES @XRES graphic // Create the graphic screen
."Kilépés: ESC\n"
 
infiniteloop: {... // infinite loop begins
myscreen @anty @antx [[]][[]] // A pixel színe amin az ant ül épp
@szin2 == { myscreen @anty @antx @szin1 [][] // másik színre átállítjuk a pixelt
2 // Jobbra fog fordulni
}{ myscreen @anty @antx @szin2 [][] // másik színre átállítjuk a pixelt
3 // Balra fog fordulni
}
// Elvégezzük az új koordináta beállítását:
sto direction
@ant 0 == { @direction 2 == then §r1 @direction 3 == then §r2 }
@ant 2 == { @direction 2 == then §r3 @direction 3 == then §r4 }
@ant 1 == { @direction 3 == { r1: antx @XRES ring 2 goto §beolvas } @direction 2 == { r2: antx @XRES !ring 3 goto §beolvas } }
@ant 3 == { @direction 3 == { r3: anty @YRES !ring 1 goto §beolvas } @direction 2 == { r4: anty @YRES ring 0 goto §beolvas } }
 
beolvas: sto ant
myscreen key? sto! billkód @pausetime usleep $1b ==
|...}
."Made " {...}§infiniteloop print ." steps.\n"
."XRES = " @XRES printnl
."YRES = " @YRES printnl
myscreen !graphic
end
{ „myscreen” }
{ „billkód” }
{ „pausetime” }
{ „XRES” }
{ „YRES” }
{ „szin1” }
{ „szin2” }
{ „ant” }
{ „antx” }
{ „anty” }
{ „direction” }
 
</syntaxhighlight>
 
=={{header|Peri}}==
<syntaxhighlight lang="peri">
###sysinclude standard.uh
###sysinclude system.uh
###sysinclude str.uh
###sysinclude X.uh
#g
$ff0000 sto szin1
$ffffff sto szin2
10 sto pausetime
//maxypixel 100 - sto YRES
//maxypixel 20 - sto YRES
//maxypixel 7 - sto YRES
//maxypixel 13 - sto YRES
maxypixel 20 - sto YRES
maxxpixel sto XRES
zero ant
// Az ant iránykódjai:
// 0 : fel
// 1 : le
// 2 : jobbra
// 3 : balra
@XRES 2 / sto antx // Az ant kezdeti koordinátái
@YRES 2 / sto anty
myscreen "Furor monitor" @YRES @XRES graphic // Create the graphic screen
."Kilépés: ESC\n"
 
{.. // infinite loop begins
myscreen @anty @antx getpixel // A pixel színe amin az ant ül épp
@szin2 == {
myscreen @anty @antx @szin1 setpixel // másik színre átállítjuk a pixelt
2 // Jobbra fog fordulni
}{
myscreen @anty @antx @szin2 setpixel // másik színre átállítjuk a pixelt
3 // Balra fog fordulni
}
// Elvégezzük az új koordináta beállítását:
sto direction
@ant 0 == @direction 2 == & { ++() antx @antx @XRES == { zero antx } 2 sto ant goto §beolvas }
@ant 0 == @direction 3 == & { @antx inv { @XRES -- sto antx }{ --() antx } 3 sto ant goto §beolvas }
@ant 1 == @direction 3 == & { ++() antx @antx @XRES == { zero antx } 2 sto ant goto §beolvas }
@ant 1 == @direction 2 == & { @antx inv { @XRES -- sto antx }{ --() antx } 3 sto ant goto §beolvas }
@ant 2 == @direction 2 == & { @anty inv { @YRES -- sto anty }{ --() anty } 1 sto ant goto §beolvas }
@ant 2 == @direction 3 == & { ++() anty @anty @YRES == { zero anty } 0 sto ant goto §beolvas }
@ant 3 == @direction 2 == & { ++() anty @anty @YRES == { zero anty } 0 sto ant goto §beolvas }
@ant 3 == @direction 3 == & { @anty inv { @YRES -- sto anty }{ --() anty } 1 sto ant goto §beolvas }
 
beolvas:
myscreen key !sto billkód @pausetime inv sleep $1b == {
."Made " {..} print ." generations.\n" {.>.} }
..}
myscreen inv graphic
end
{ „myscreen” }
{ „billkód” }
{ „pausetime” }
{ „XRES” }
{ „YRES” }
{ „szin1” }
{ „szin2” }
{ „ant” }
{ „antx” }
{ „anty” }
{ „direction” }
</syntaxhighlight>
 
=={{header|Gambas}}==
<langsyntaxhighlight lang="gambas">'This code will create a GUI Form to display the result
 
hGridView As GridView 'The display is on a GridView
Line 3,398 ⟶ 4,006:
End With
 
End</langsyntaxhighlight>
'''[http://www.cogier.com/gambas/Langton's%20ant.png Click here for an image of the result]'''
 
Line 3,405 ⟶ 4,013:
To make it easier to see the output on small Atari screens, the output is written to a text file.
 
<langsyntaxhighlight lang="basic">
'
' Langton's ant
Line 3,499 ⟶ 4,107:
WEND
RETURN
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
[[file:GoAnt.png|right|thumb|Output png]]
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,555 ⟶ 4,163:
fmt.Println(err)
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 3,562 ⟶ 4,170:
Necessary import:
 
<langsyntaxhighlight Haskelllang="haskell">import Data.Set (member,insert,delete,Set)</langsyntaxhighlight>
 
In order to express the ant's algorithm literally we define two operators:
 
<langsyntaxhighlight Haskelllang="haskell">-- functional sequence
(>>>) = flip (.)
 
-- functional choice
p ?>> (f, g) = \x -> if p x then f x else g x</langsyntaxhighlight>
 
Finally define the datatype representing the state of ant and ant's universe
<langsyntaxhighlight Haskelllang="haskell">data State = State { antPosition :: Point
, antDirection :: Point
, getCells :: Set Point }
 
type Point = (Float, Float)</langsyntaxhighlight>
 
Now we are ready to express the main part of the algorithm
<langsyntaxhighlight Haskelllang="haskell">step :: State -> State
step = isBlack ?>> (setWhite >>> turnRight,
setBlack >>> turnLeft) >>> move
Line 3,589 ⟶ 4,197:
turnRight (State p (x,y) m) = State p (y,-x) m
turnLeft (State p (x,y) m) = State p (-y,x) m
move (State (x,y) (dx,dy) m) = State (x+dx, y+dy) (dx, dy) m</langsyntaxhighlight>
 
That's it.
 
Here is the solution of the task:
<langsyntaxhighlight Haskelllang="haskell">task :: State -> State
task = iterate step
>>> dropWhile ((< 50) . distance . antPosition)
>>> getCells . head
where distance (x,y) = max (abs x) (abs y)</langsyntaxhighlight>
 
For given initial configuration it returns the set of black cells at the end of iterations.
 
We can display it graphically using Gloss library
<langsyntaxhighlight lang="haskell">import Graphics.Gloss
 
main = display w white (draw (task initial))
Line 3,610 ⟶ 4,218:
initial = State (0,0) (1,0) mempty
draw = foldMap drawCell
drawCell (x,y) = Translate (10*x) (10*y) $ rectangleSolid 10 10</langsyntaxhighlight>
 
Or animate the ant's trajectory
<langsyntaxhighlight lang="haskell">main = simulate w white 500 initial draw (\_ _ -> step)
where
w = InWindow "Langton's Ant" (400,400) (0,0)
initial = State (0,0) (1,0) mempty
draw (State p _ s) = pictures [foldMap drawCell s, color red $ drawCell p]
drawCell (x,y) = Translate (10*x) (10*y) $ rectangleSolid 10 10</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
[[file:LangtonsAnt_unicon_100x100_11655.gif|right|thumb]]
<langsyntaxhighlight Iconlang="icon">link graphics,printf
 
procedure main(A)
Line 3,673 ⟶ 4,281:
WAttrib(label)
WDone()
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 3,681 ⟶ 4,289:
=={{header|J}}==
 
<langsyntaxhighlight lang="j">dirs=: 0 1,1 0,0 _1,:_1 0
langton=:3 :0
loc=. <.-:$cells=. (_2{.y,y)$dir=. 0
Line 3,691 ⟶ 4,299:
end.
' #' {~ cells
)</langsyntaxhighlight>
 
<pre style="font-size: 2px"> langton 100 100
Line 3,797 ⟶ 4,405:
=={{header|Java}}==
This implementation allows for sizes other than 100x100, marks the starting position with a green box (sometimes hard to see at smaller zoom levels and the box is smaller than the "pixels" so it doesn't cover up the color of the "pixel" it's in), and includes a "zoom factor" (<code>ZOOM</code>) in case the individual "pixels" are hard to see on your monitor.
<langsyntaxhighlight lang="java">import java.awt.Color;
import java.awt.Graphics;
 
Line 3,864 ⟶ 4,472:
return plane;
}
}</langsyntaxhighlight>
Output (click for a larger view):
 
Line 3,873 ⟶ 4,481:
Utilises the HTML5 canvas element to procedurally generate the image... I wanted to see the progress of the grid state as it was generated, so this implementation produces a incrementally changing image until an 'ant' hits a cell outside of the coordinate system. It can also accept multiple ants, this adds minimal complexity with only the addition of an 'ants' array which is iterated in each step, no additional conditions are necessary to simulate multiple ants, they coexist quite well... good ants ! 1st argument is an array of ant objects, 2nd argument is an object property list of options to change grid size, pixel size and interval (animation speed).
 
<syntaxhighlight lang="javascript">
<lang JavaScript>
// create global canvas
var canvas = document.createElement('canvas');
Line 3,975 ⟶ 4,583:
simulate();
}
</syntaxhighlight>
</lang>
 
Usage: default ants, custom opts
 
<syntaxhighlight lang="javascript">
<lang JavaScript>
langtonant({}, {
gridsize: 100,
Line 3,985 ⟶ 4,593:
interval: 4
});
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,995 ⟶ 4,603:
Usage: custom ants, default opts
 
<syntaxhighlight lang="javascript">
<lang JavaScript>
langtonant([
{
Line 4,015 ⟶ 4,623:
}
]);
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,027 ⟶ 4,635:
Requires lodash. Wants a canvas with id = "c"
 
<langsyntaxhighlight lang="javascript">
///////////////////
// LODASH IMPORT //
Line 4,096 ⟶ 4,704:
 
updateWorld(world, ant, RUNS);
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
In the following, the grid is boolean, and white is represented by true.
<syntaxhighlight lang="jq">
<lang jq>
def matrix(m; n; init):
if m == 0 then [range(0;n)] | map(init)
Line 4,111 ⟶ 4,719:
| ($grid|length) as $height
| ($grid[0]|length) as $width
| reduce range(0;$height) as $i ("\u001BHu001B[H"; # ANSI code
. + reduce range(0;$width) as $j ("\n";
. + if $grid[$i][$j] then " " else "#" end ) );
Line 4,158 ⟶ 4,766:
;
langtons_ant(100)</langsyntaxhighlight>
{{Out}}
The output is the same as for [[#Rexx|Rexx]] below.
Line 4,164 ⟶ 4,772:
=={{header|Julia}}==
{{works with|Julia|1.0}}
<syntaxhighlight lang="julia">
<lang Julia>
function ant(width, height)
y, x = fld(height, 2), fld(width, 2)
Line 4,183 ⟶ 4,791:
 
ant(100, 100)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|D}}
<langsyntaxhighlight lang="scala">// version 1.2.0
 
enum class Direction { UP, RIGHT, DOWN, LEFT }
Line 4,220 ⟶ 4,828:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,226 ⟶ 4,834:
Same as D entry (textual version)
</pre>
 
"Go to the ant, O sluggard; consider her ways, and be wise. Without having any chief, officer, or ruler, she prepares her bread in summer and gathers her food in harvest." For Dr. Kaser.
 
=={{header|LC-3}}==
"Go to the ant, O sluggard; consider her ways, and be wise. Without having any chief, officer, or ruler, she prepares her bread in summer and gathers her food in harvest." For Dr. Kaser.
 
<syntaxhighlight lang="lc-3">
 
.orig x3000
ld r1, ASCIIDIFF1
 
; user input for grid size
lea r0, STGRIDSIZE
puts
in
 
add r0, r0, r1
add r0, r0, #-1
brz SELECTED100
ld r0, GRID300
st r0, GRIDSIZE
brnzp GRIDSELECTED
 
SELECTED100
ld r0, GRID100
st r0, GRIDSIZE
 
GRIDSELECTED
 
; User input for number of additional ants
lea r0, STHOWMANY
puts
in
add r1, r1, r0 ; r1 = number of additional ants
add r1, r1, #1
st r1, LIVINGANTS
 
; INITIALIZE FIRST ANT
and r7, r7, x0
add r7, r7, #9 ; loop counter for the other ants
 
and r1, r1, x0  ; x and y coordinates go in here
and r3, r3, x0  ; to be mapped to a cell id
 
; check grid size for starting coordinates
ld r4, GRIDSIZE
ld r6, GRID100
not r6, r6
add r6, r6, #1
add r6, r6, r4  ; grid size - 100
brz GRID100B
 
ld r1, START300
ld r3, START300
brnzp FIRSTANTCOORDINATES
 
GRID100B
ld r1, START100
ld r3, START100
 
FIRSTANTCOORDINATES
 
JSR MAPPY   ; takes r1 and r3 values, converts to cell id in r5
 
ld r6, LIVEANTTEMPLATE  ; = x8000, alive and facing north
add r6, r6, r5  ; complete antword for ant 1
lea r4, ANTWORD
str r6, r4, #0  ; put first ant in base address of ANTWORD array
 
 
ld r2, LIVINGANTS
ANTSETUPLOOP
add r4, r4, #1  ;   increment address of ant
 
add r2, r2, #-1
brnz INITIALIZEDEAD
JSR ANTCOORDS
JSR MAPPY
ld r6, LIVEANTTEMPLATE
add r6, r5, r6
brnzp READYTOSTORE
 
INITIALIZEDEAD
and r6, r6, x0
 
READYTOSTORE
str r6, r4, #0
 
 
add r7, r7, #-1
brnz DONESETUP
brnzp ANTSETUPLOOP
 
DONESETUP
 
 
 
 
 
 
 
BIGMOVELOOP ; one iteration of this loop moves all 10 ants (doing nothing if they're dead)
ld r1, LIVINGANTS
brz EVERYONEISDEAD
ld r1, ANTWORD
 
 
; FOR LOOP TO MOVE ALL 10 ANTS
 
 
 
 
 
ld r1, STEPCOUNT
add r1, r1, #1
st r1, STEPCOUNT
 
BRNZP BIGMOVELOOP
EVERYONEISDEAD ; :(
 
 
 
 
halt
STGRIDSIZE .stringz "Grid size? 1 for 100, 3 for 300 "
STHOWMANY .stringz "How many additional ants? "
ASCIIDIFF1 .fill #-48
SUBTEMP1 .fill #0
LIVINGANTS .fill #0
GRIDSIZE .fill #0
GRID100 .fill #100
GRID300 .fill #300
STEPCOUNT .fill #0
ANTWORD .blkw #10
START100 .fill #50
START300 .fill #150
LIVEANTTEMPLATE .fill x8000
ANTCOORDTEMP .fill #0
ANTCOORDTEMP2 .fill #0
 
 
 
 
 
 
 
 
 
;************************************************************************
;************************************************************************
;                             SUBROUTINES
;************************************************************************
;************************************************************************
 
; SUBROUTINE
ANTSONTHEMOVE
; [1] check if dead
; [2] extract current location
; [3] extract current direction
; [4] check current colour
; [5] turn
; [7] change location or kill
 
; INPUT: R1:
address of ant
;        R4:
grid size
 
; LOCAL: R2: ant word
;           R3: cell id of ant
 
st r2, MOVETEMP2
st r3, MOVETEMP3
st r5, MOVETEMP5
st r6, MOVETEMP6
st r7, MOVETEMP7
ldr r2, r1, #0 ; r2 = copy of ant-word
 
; [1] CHECK FOR DEATH. word for dead ants == x0000
add r2, r2, #0
brz ENDOFMOVE ; if ant-word + 0 == 0, ant is dead.
 
; [2] extract current location
ld r3, IDMASK ; for getting rid of first 3 bits of ant-word, leaving only location
and r3, r2, r3 ; r3 = cell id of ant
 
; [4] check current colour and flip it
 
 
jsr FLIPPITY    ; flips bit, puts original colour in R5
                ; white/0: turn right; black/1: turn left
 
; [5] turn the ant according to pre-flipped colour
 
add r0, r5, #0
brnp LEFTTURN
 
jsr TAKEARIGHTTURN
brnzp DONETURNING
 
LEFTTURN
jsr TAKEALEFTTURN
DONETURNING
 
; [7] change location and kill
 
ldr r2, r1, #0 ; reload modified antword from memory
 
ld r5, SOUTH    ; butmasks
ld r6, EAST
 
and r5, r5, r2
and r6, r6, r2  ; isolating the two direction bits, 2b and 3b, to determine direction
 
add r5, r5, #0  ;    check if 2b is 0
brnp SECTIOND   ;
add r6, r6, #0  ;   check if 3b is 0
brnp SECTIONC
 
 
; if both are zero, direction is north
;; if cell id <= grid size, ant is already at the top and will die
not r0, r4
add r0, r0, #1  ; r0 = negative grid size
add r3, r0, r3  ; r3 = cell id - grid
brn ANTDEATHISPERMANENT ; if negative, kill it
add r2, r2, r0  ; antword - grid size
brnzp ENDOFMOVE
 
 
 
SECTIONC
; if direction is 01, ant faces east
;; if (cellID % grid != grid -1)
;; then cellid++, else die
not r0, r4
add r0, r0, #1
 
add r5, r3, #0  ;    copy celll id to r5 to repeatedly subtract grid size
EASTMODLOOP
add r5, r5, r0  ;   cell id - grid
add r5, r5, #1  ; if this is 0, then r5 == grid - 1
brz ANTDEATHISPERMANENT
add r5, r5, #-1 ; but if not, undo it and re-loop
brn MOVEEAST    ; if negative, allowed to move east
                ; if equal to grid-1, ant is on eastern border and will die
 
BRNZP EASTMODLOOP
 
MOVEEAST
add r2, r2, #1  ; move east: CellID++
brnzp ENDOFMOVE
 
SECTIOND    ; first direction bit is 1
add r6, r6, #0  ; check if second bit is 0
brnp SECTIONF
; if it is 0, then direction is 10 = south
; if ant is on southern border, it dies
; if cellID >= grid^2-grid, then ant is on southern border
 
ld r0, N100
add r0, r0, r3  ; checking if grid size = 100
brz GRIDIS100
ld r0, GRIDSQ300HALF
add r3, r3, r0
add r3, r3, r0
add r3, r3, r0
add r3, r3, r0
brzp ANTDEATHISPERMANENT
add r2, r2, r4
brnzp ENDOFMOVE
 
GRIDIS100
ld r0, GRIDSQ100
add r3, r3, r0
brzp ANTDEATHISPERMANENT
add r2, r2, r4
brnzp ENDOFMOVE
 
 
SECTIONF
; direction bits are 11 = WEST
; if cellID % grid != 0, ant can go west, otherwise dead
 
add r6, r3, #0  ; copy cell id to r6
not r0, r4
add r0, r0, #1  ; r0 = -grid
WESTMODLOOP
add r6, r6, r0
brz ANTDEATHISPERMANENT
brn CANMOVEWEST
brp WESTMODLOOP
 
CANMOVEWEST
add r2, r2, #-1
brnzp ENDOFMOVE
 
 
ANTDEATHISPERMANENT
and r2, r2, #0
ld r7, LIVINGANTS
add r7, r7, #-1
st r7, LIVINGANTS
 
ENDOFMOVE
str r1, r2, #0  ;    double check this syntax
ld r2, MOVETEMP2
ld r3, MOVETEMP3
ld r5, MOVETEMP5
ld r6, MOVETEMP6
ld r7, MOVETEMP7
RET
 
N100 .fill #-100
GRIDSQ100 .fill #-9900
GRIDSQ300HALF .fill #-22425
MOVETEMP3 .fill #0
MOVETEMP2 .fill #0
MOVETEMP4 .fill #0
MOVETEMP5 .fill #0
MOVETEMP6 .fill #0
MOVETEMP7 .fill x0
IDMASK .fill x1FFF    ;   for extracting bits 12-0, the cell ID of the ant
 
; end of ANTSONTHEMOVE subroutine
 
 
 
 
 
FAKEXOR ; subroutine
 
; XOR of two registers
; INPUT r2, r4
; OUTPUT r6 = r2 XOR r4
 
; A in r4, not A in r5
; B in r2; not B in r6
; r4 XOR r2
 
st r5, XORTEMP5
 
not r6, r2
and r6, r6, r4  ; r6 = a & ~b
not r6, r6      ; r6 = ~(a & ~b)
 
not r5, r4      ; r5 = ~ a
and r5, r5, r2  ; r5 = ~a & b
not r5, r5      ; r5 = ~(~a & b)
and r6, r5, r6  ; r6 = ~(a & ~b) & ~(~a & b)
not r6, r6      ; r6 = ~( ~(a & ~b) & ~(~a & b) ) = a XOR b
 
ld r5, XORTEMP5
 
RET 
 
XORTEMP5 .fill #0
 
 
; SUBROUTINE
 FLIPPITY
; Takes a cell id and flips the bit in the grid, returns the original colour
; INPUT     r1: cell id
; LOCAL     r2: which bit to flip, then bitmask
;           r3: quotient, then address of byte to change
; OUTOUT    r5: original colour of cell id, before flipping. 1 if black, 0 if white.
;
; First, get byte (GRID + OFFSET)
; CELL ID / 16
 
st r4, FLIPTEMP4
st r5, FLIPTEMP5
st r6, FLIPTEMP6
 
and r3, r3, #0
add r2, r1, #0  ; copy cell id into r2
 
; loop to divide cellid by 16
FLIPLOOP
add r2, r2, #-16 ; cell id - 16
brn FLIPLOOPDONE    ; if negative, division done
add r3, r3, #1      ; if not negative, increment quotient and subtract again
BRNZP FLIPLOOP
 
FLIPLOOPDONE
add r2, r2, #8      ; add 16 back to negative number to get cellid % 16
add r2, r2, #8      ; this is which bit within the byte that the cell ID refers to
 
lea r4, GRID        ; starting address of GRID array
add r3, r3, r4      ; r3 = address of byte that will be changed = GRID base address + CELL ID / 16
 
 
lea r4, BM1         ; r4 = address of butmask array
add r4, r4, r2      ; r4 + which bit to flip = address of appropriate bitmask
ldr r2, r4, #0      ; r2 = bitmask to flip one bit
 
ldr r4, r3, #0      ; r4 = byte to be changed
 
and r0, r2, r4      ; indicates original colour of bit. 0 if white, non-zero if black
 
; A in r4, not A in r5
; B in r2; not B in r6
; r4 XOR r2
not r6, r2
and r6, r6, r4  ; r6 = a & ~b
not r6, r6      ; r6 = ~(a & ~b)
 
not r5, r4      ; r5 = ~ a
and r5, r5, r2  ; r5 = ~a & b
not r5, r5      ; r5 = ~(~a & b)
and r6, r5, r6  ; r6 = ~(a & ~b) & ~(~a & b)
not r6, r6      ; r6 = ~( ~(a & ~b) & ~(~a & b) ) = a XOR b
 
 
str r6, r3, #0
 
ld r4, FLIPTEMP4
ld r6, FLIPTEMP6
 
add r5, r0, #0  ; move colour of bit into r5 for output
 
ret
GRID .fill x8000
FLIPTEMP4 .fill #0
FLIPTEMP5 .fill #0
FLIPTEMP6 .fill #0
 
; bitmasks for flipping one bit
BM1 .fill x8000
BM2 .fill x4000
BM3 .fill x2000
BM4 .fill x1000
BM5 .fill x0800
BM6 .fill x0400
BM7 .fill x0200
BM8 .fill x0100
BM9 .fill x0080
BM10 .fill x0040
BM11 .fill x0020
BM12 .fill x0010
BM13 .fill x0008
BM14 .fill x0004
BM15 .fill x0002
BM16 .fill x0001
 
; END OF FLIPPITY SUBROUTINE
 
 
 
 
 
; SUBROUTINE
TAKEALEFTTURN
; turns the ant 90 degrees left
 
; INPUT R1: address in memory of ANT
; LOCAL R2: ant
;       R3: bitmask
;       R4: 3rdbit
;       R5: 2nd and 3rd bit
;       R6:
;       R7:
;       R0:
 
st r2, LEFTTURNTEMP2
st r3, LEFTTURNTEMP3
st r4, LEFTTURNTEMP4
st r6, LEFTTURNTEMP6
st r7, LEFTTURNTEMP7  ;  store r7, load before RET
ldr r2, r1, #0  ;  load ant into r2
ld r3, EAST
and r4, r2, r3 ; r4 = 3rdbit
 
ld r3, WEST
;and r5, r2, r3 ; r5 = 2nd and 3rd bits
 
 
add r4, r4, #0 ; check if 3rd bit is 0
brnp THIRDBIT1  ; If so, continue. If not, jump to next part.
; 3rd bit is 0, so XOR r2 ant-word with WEST bitmask, already in R3
 
BRNZP LEFTTURNEND
 
THIRDBIT1
; third bit is 1, so use EAST bitmask
ld r3, EAST
 
LEFTTURNEND
 
add r0, r4, #0  ; move r4 3rdbit into r0 temporarily
add r4, r3, #0  ; move r3 bitmask into r4 for the XOR subroutine
JSR FAKEXOR   ; r6 = r2 XOR r4
              ; flips the correct bit to turn left
 
add r3, r4, #0 ; moves r4 bitmask back into r3
add r4, r0, #0  ; moves r0 3rdbit back into r3
 
str r6, r1, #0  ; store tweaked ant-word with new direction back in memory
 
ld r2, LEFTTURNTEMP2
ld r3, LEFTTURNTEMP3
ld r4, LEFTTURNTEMP4
ld r6, LEFTTURNTEMP6
ld r7, LEFTTURNTEMP7
RET
 
 
WEST .fill X6000
EAST .fill x2000
NORTH .fill x0000
SOUTH .fill x4000
 
LEFTTURNTEMP2 .fill #0
LEFTTURNTEMP3 .fill #0
LEFTTURNTEMP4 .fill #0
LEFTTURNTEMP6 .fill #0
LEFTTURNTEMP7 .fill #0
 
; end of TAKEALEFTTURN subroutine
 
 
 
; SUBROUTINE
TAKEARIGHTTURN
; turns the ant 90 degrees right
 
; INPUT R1: address in memory of ANT
; LOCAL R2: ant
;       R3: bitmask
;       R4: 3rdbit
;   R5: 2nd and 3rd bit
;   R6:
;   R7:
;   R0:
 
st r2, RIGHTTURNTEMP2
st r3, RIGHTTURNTEMP3
st r4, RIGHTTURNTEMP4
st r6, RIGHTTURNTEMP6
st r7, RIGHTTURNTEMP7  ;  store r7, load before RET
ldr r2, r1, #0  ;  load ant into r2
ld r3, EAST
and r4, r2, r3 ; r4 = 3rdbit
 
;ld r3, WEST
;and r5, r2, r3 ; r5 = 2nd and 3rd bits
 
 
add r4, r4, #0 ; check if 3rd bit is 0
brnp THIRDBIT1RIGHT  ; If so, continue. If not, jump to next part.
; 3rd bit is 0, so XOR r2 ant-word with EAST bitmask
ld r3, EAST
 
BRNZP RIGHTTURNEND
 
THIRDBIT1RIGHT
; third bit is 1, so use WEST bitmask
ld r3, WEST
 
RIGHTTURNEND
 
add r0, r4, #0  ; move r4 3rdbit into r0 temporarily
add r4, r3, #0  ; move r3 bitmask into r4 for the XOR subroutine
JSR FAKEXOR   ; r6 = r2 XOR r4
              ; flips the correct bit to turn right
 
add r3, r4, #0 ; moves r4 bitmask back into r3
add r4, r0, #0  ; moves r0 3rdbit back into r3
 
str r6, r1, #0  ; store modified ant-word with new direction back in memory
 
ld r2, RIGHTTURNTEMP2
ld r3, RIGHTTURNTEMP3
ld r4, RIGHTTURNTEMP4
ld r6, RIGHTTURNTEMP6
ld r7, RIGHTTURNTEMP7
RET
 
RIGHTTURNTEMP2 .fill #0
RIGHTTURNTEMP3 .fill #0
RIGHTTURNTEMP4 .fill #0
RIGHTTURNTEMP6 .fill #0
RIGHTTURNTEMP7 .fill #0
 
; end of TAKEARIGHTTURN subroutine
 
 
 
 
 
 
 
 
 
; SUBROUTINE
ANTCOORDS
; INPUT     r2: index of ant
; OUTPUT    r1: x coordinate value
;           r3: y coordinate value
; "Enter x coordinates for ant #whatever"
 
st r4, COORD2
 
ld r0, NEWLINE
out
lea r0, ENTERXCOORDS
puts
ld r3, ASCIIPLUS
;add r0, r2, r3
;out
ld r0, NEWLINE
out
 
 
ld r5, ASCIIDIFF 
getc
out
add r4, r0, r5  ; r4 holds first digit of x
 
add r1, r4, r4  ; r1 = 2 * r4
add r1, r1, r1  ; r1 = 4 * r4
add r1, r1, r1  ; r1 = 8 * r4
add r1, r1, r4  ; r1 = 9 * r4
add r1, r1, r4  ; r1 = 10 * r4
 
 
 
getc
out
add r4, r0, r5  ; r4 holds 2nd digit of x
add r1, r1, r4  ; full value of x coordt
st r1, COORD1
 
 
; "enter y coords"
ld r0, NEWLINE
out
lea r0, ENTERYCOORDS
puts
ld r3, ASCIIPLUS
;add r0, r2, r3
;out
ld r0, NEWLINE
out
 
ld r5, ASCIIDIFF 
getc
out
add r4, r0, r5  ; r4 holds first digit of y
 
add r1, r4, r4  ; r1 = 2 * r4
add r1, r1, r1  ; r1 = 4 * r4
add r1, r1, r1  ; r1 = 8 * r4
add r1, r1, r4  ; r1 = 9 * r4
add r1, r1, r4  ; r1 = 10 * r4
 
 
getc
out
add r4, r0, r5  ; r4 holds 2nd digit of y
add r3, r1, r4  ; full value of y coord
ld r1, COORD1
ld r4, COORD2
RET
 
 
ENTERXCOORDS .STRINGZ "Enter x coordinates for ant "
ENTERYCOORDS .STRINGZ "Enter y coordinates for ant "
ASCIIDIFF .fill #-48
ASCIIPLUS .fill #48
COORD1 .fill #0
NEWLINE .fill #10
COORD2 .fill #0
COORD3 .fill #0
 
; END OF ANT_COORDINATES_SUBROUTINE
 
 
 
 
MAPPY
; Maps the coordinates of the ant
; Input:  R1: x coord
;  R3: y coord
;  R4: grid size
; Output: R5: Cell ID
; Cell ID = grid size * y coord + x coord
 
st r6, MAP1
st r7, MAP2
 
; multiply by 100
add R0, R3, R3 ; 2y
add R0, R0, R0 ; 4y
add R6, R0, R0 ; 8y
add R6, R6, R6 ; 16y
add R6, R6, R6 ; 32y
add R0, R0, R6 ; 36y
add R6, R6, R6 ; 64y
add R0, R0, R6 ; 100y
 
ld R7, N100a
add R7, R4, R7
 
brz GRID100a
add R0, R0, R0 ;200y
add R0, R0, R3 ;300y
 
GRID100a
Add R5, R0, R1  ; OUTPUT: R5 = grid*y + x
 
 
ld r6, MAP1
ld r7, MAP2
RET
N100a .fill #-100
MAP1 .fill #0
MAP2 .fill #0
 
; END OF MAPPY SUBROUTINE
 
 
 
.end
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
Native graphics.
[[Image:langtonsant.png]]
<langsyntaxhighlight lang="lb">dim arena(100,100)
black=0
white=not(black)
Line 4,285 ⟶ 5,618:
end
end sub
</langsyntaxhighlight>
 
Text version.
<syntaxhighlight lang="lb">
<lang lb>
'move up=1 right=2 down=3 left=4
' ---------------------------------
Line 4,317 ⟶ 5,650:
next x
</langsyntaxhighlight>
 
=={{header|Locomotive Basic}}==
 
<langsyntaxhighlight lang="locobasic">10 mode 1:defint a-z:deg
20 ink 1,0:ink 0,26
30 x=50:y=50:ang=270
Line 4,334 ⟶ 5,667:
120 y=y+cos(ang)
130 if x<1 or x>100 or y<1 or y>100 then end
140 goto 70</langsyntaxhighlight>
 
Output:
Line 4,341 ⟶ 5,674:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">make "size 100
make "white 1
make "black 2
Line 4,391 ⟶ 5,724:
]
]
bye</langsyntaxhighlight>
 
{{Output}}
Line 4,449 ⟶ 5,782:
=={{header|LOLCODE}}==
 
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.3
 
I HAS A plane ITZ A BUKKIT
Line 4,487 ⟶ 5,820:
IM OUTTA YR printer BTW, UR OUTTA CYAN
 
KTHXBYE</langsyntaxhighlight>
 
=={{header|Lua}}==
For this example, the lua Socket and Curses modules and a terminal with enough lines are needed.
<langsyntaxhighlight LUAlang="lua">local socket = require 'socket' -- needed for socket.sleep
local curses = require 'curses' -- used for graphics
 
Line 4,598 ⟶ 5,931:
socket.sleep(naptime)
until false
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Ant {
Form 120,102
Line 4,658 ⟶ 5,991:
}
Ant
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,746 ⟶ 6,079:
</pre >
 
=={{header|Mathematicamake}}==
[[File:make_langton_ant.png|right]]
<syntaxhighlight lang="make"># Langton's ant Makefile
# netpbm is an ancient collection of picture file formats
# convert and display are from imagemagick
.PHONY: display
display: ant.png
display $<
ant.png: ant.pbm
convert $< $@
 
n9:=1 2 3 4 5 6 7 8 9
n100:=$(n9) $(foreach i,$(n9),$(foreach j,0 $(n9),$i$j)) 100
ndec:=0 $(n100)
ninc:=$(wordlist 2,99,$(n100))
$(foreach i,$(n100),$(eval row$i:=$(foreach j,$(n100),0)))
 
.PHONY: $(foreach i,$(ndec),row$i)
row0:
@echo >ant.pbm P1
@echo >>ant.pbm '#' Langton"'"s ant
@echo >>ant.pbm 100 100
rowrule=row$i: row$(word $i,$(ndec)); @echo >>ant.pbm $$($$@)
$(foreach i,$(n100),$(eval $(rowrule)))
ant.pbm: Makefile row100
@:
 
x:=50
y:=50
direction:=1
 
turn=$(eval direction:=$(t$(xy)$(direction)))
xy=$(word $x,$(row$y))
t01:=4
t02:=1
t03:=2
t04:=3
t11:=2
t12:=3
t13:=4
t14:=1
 
flip=$(eval row$y:=$(start) $(not$(xy)) $(end))
start=$(wordlist 1,$(word $x,$(ndec)),$(row$y))
not0:=1
not1:=0
end=$(wordlist $(word $x,$(ninc) 100),100,$(row$y))
 
step=$(eval $(step$(direction)))
step1=y:=$(word $y,exit $(n100))
step2=x:=$(word $x,$(ninc) exit)
step3=y:=$(word $y,$(ninc) exit)
step4=x:=$(word $x,exit $(n100))
 
iteration=$(if $(filter exit,$x $y),,$(turn)$(flip)$(step))
$(foreach i,$(n100) $(n100),$(foreach j,$(n100),$(iteration)))
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
[[File:LangtonsAnt.png|right|thumb|Output]]
 
<langsyntaxhighlight lang="mathematica">direction = 1;
data = SparseArray[{{50, 50} -> -1}, {100, 100}, 1];
NestWhile[
{Re@#, Im@#} &@(direction *= (data[[Sequence @@ #]] *= -1) I) + # &,
{50, 50}, 1 <= Min@# <= Max@# <= 100 &];
Image@data</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function u = langton_ant(n)
if nargin<1, n=100; end;
A = sparse(n,n); % white
Line 4,777 ⟶ 6,168:
if (~mod(k,100)),spy(A);pause(.1);end; %display after every 100 interations
end;
end</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import strutils, sequtils
 
type
Line 4,799 ⟶ 6,190:
 
var i = 0
while i < maxSteps and x in 0 .. < width and y in 0 .. < height:
let turn = m[y][x] == black
m[y][x] = if m[y][x] == black: white else: black
Line 4,814 ⟶ 6,205:
for row in m:
echo map(row, proc(x: Color): string =
if x == white: "." else: "#").join("")</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">open Graphics
 
type dir = North | East | South | West
Line 4,849 ⟶ 6,240:
if not(key_pressed()) then loop (move pos dir) dir
in
loop (size_x()/2, size_y()/2) North</langsyntaxhighlight>
 
Run with:
Line 4,855 ⟶ 6,246:
 
=={{header|Octave}}==
<langsyntaxhighlight OCTAVElang="octave">clear
E=100 % Size of lattice.
N=11200 % Number of iterations.
Line 4,866 ⟶ 6,257:
endfor;
imagesc(reshape(z,E,E)) % Draw the Lattice
</syntaxhighlight>
</lang>
 
=={{header|Ol}}==
{{libheader|OpenGL}}
<langsyntaxhighlight lang="scheme">
#!/usr/bin/ol
(import (otus random!))
Line 4,942 ⟶ 6,333:
 
)))
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
[[File:Langton-pari.png|right|thumb]]
<langsyntaxhighlight lang="parigp">langton()={
my(M=matrix(100,100),x=50,y=50,d=0);
while(x && y && x<=100 && y<=100,
Line 4,960 ⟶ 6,351:
plothraw(u,v)
};
show(langton())</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 4,970 ⟶ 6,361:
{{works with|Turbo Pascal}} Except, the green arrow on step 4 does not appear!
 
<syntaxhighlight lang="pascal">
<lang Pascal>
{$B- Early and safe resolution of If x <> 0 and 1/x...}
Program LangtonsAnt; Uses CRT;
Line 5,084 ⟶ 6,475:
 
END.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use strict;
# Perl 5 implementation of Langton's Ant
Line 5,127 ⟶ 6,518:
}
print "\n";
}</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence grid = repeat(repeat(' ',100),100)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">grid</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #000000;">100</span><span style="color: #0000FF;">),</span><span style="color: #000000;">100</span><span style="color: #0000FF;">)</span>
integer aX = 50, aY = 50,
<span style="color: #004080;">integer</span> <span style="color: #000000;">aX</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">50</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">aY</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">50</span><span style="color: #0000FF;">,</span>
gXY, angle = 1 -- ' '/'#'; 0,1,2,3 = NESW
<span style="color: #000000;">gXY</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">angle</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span> <span style="color: #000080;font-style:italic;">-- ' '/'#'; 0,1,2,3 = NESW</span>
constant dX = {0,-1,0,1} -- (dY = reverse(dX))
<span style="color: #008080;">constant</span> <span style="color: #000000;">dX</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- (dY = reverse(dX))</span>
while aX>=1 and aX<=100
<span style="color: #008080;">while</span> <span style="color: #000000;">aX</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">aX</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">100</span>
and aY>=1 and aY<=100 do
<span style="color: #008080;">and</span> <span style="color: #000000;">aY</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">aY</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
gXY = grid[aX][aY]
<span style="color: #000000;">gXY</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">grid</span><span style="color: #0000FF;">[</span><span style="color: #000000;">aX</span><span style="color: #0000FF;">][</span><span style="color: #000000;">aY</span><span style="color: #0000FF;">]</span>
grid[aX][aY] = 67-gXY -- ' '<=>'#', aka 32<->35
<span style="color: #000000;">grid</span><span style="color: #0000FF;">[</span><span style="color: #000000;">aX</span><span style="color: #0000FF;">][</span><span style="color: #000000;">aY</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">67</span><span style="color: #0000FF;">-</span><span style="color: #000000;">gXY</span> <span style="color: #000080;font-style:italic;">-- ' '&lt;=&gt;'#', aka 32&lt;-&gt;35</span>
angle = mod(angle+2*gXY+3,4) -- +/-1, ie 0,1,2,3 -> 1,2,3,0 or 3,0,1,2
<span style="color: #000000;">angle</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">angle</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">gXY</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- +/-1, ie 0,1,2,3 -&gt; 1,2,3,0 or 3,0,1,2</span>
aX += dX[angle+1]
<span style="color: #000000;">aX</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">dX</span><span style="color: #0000FF;">[</span><span style="color: #000000;">angle</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
aY += dX[4-angle]
<span style="color: #000000;">aY</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">dX</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">-</span><span style="color: #000000;">angle</span><span style="color: #0000FF;">]</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
puts(1,join(grid,"\n"))</lang>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">grid</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">))</span>
<!--</syntaxhighlight>-->
{{out}}
<pre style="font-size: 2px">
Line 5,208 ⟶ 6,601:
''to the halves of width and height.)''<br>
<br>
<langsyntaxhighlight lang="php">
// INIT AND DEFINITION
define('dest_name', 'output.png'); // destination image
Line 5,260 ⟶ 6,653:
// SAVE IMAGE
imagepng($img, dest_name);
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
[[File:Picolisp_ant.gif|right|thumb]]
This code pipes a PBM into ImageMagick's "display" to show the result:
<langsyntaxhighlight PicoLisplang="picolisp">(de ant (Width Height X Y)
(let (Field (make (do Height (link (need Width)))) Dir 0)
(until (or (le0 X) (le0 Y) (> X Width) (> Y Height))
Line 5,282 ⟶ 6,675:
(out '(display -) (ant 100 100 50 50))
(bye)
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
To simplify the steps within the loop, -1 and 1 are used to represent the binary state of the spaces in the grid. As neither state is now a default value, to simplify setting the starting states, an array of arrays is used instead of a two dimensional array.
<syntaxhighlight lang="powershell">
<lang PowerShell>
$Size = 100
 
Line 5,315 ⟶ 6,708:
# Convert to strings for output
ForEach ( $Row in $G ) { ( $Row | ForEach { ( ' ', '', '#')[$_+1] } ) -join '' }
</syntaxhighlight>
</lang>
{{out}}
Default PowerShell console colors reverse the colors from black on white to white on dark blue. Most blank lines not included below.
Line 5,376 ⟶ 6,769:
=={{header|Processing}}==
Processing implementation, this uses two notable features of Processing, first of all, the animation is calculated with the draw() loop, second the drawing on the screen is also used to represent the actual state.
<langsyntaxhighlight lang="processing">/*
* we use the following conventions:
* directions 0: up, 1: left, 2: down: 3: right
Line 5,456 ⟶ 6,849:
void setBool(int x, int y, boolean white) {
set(x,y,white?#ffffff:#000000);
}</langsyntaxhighlight>
 
==={{header|Processing Python mode}}===
<langsyntaxhighlight lang="python">"""
we use the following conventions:
directions 0: up, 1: left, 2: down: 3: right
Line 5,525 ⟶ 6,918:
 
def setBool(x, y, white):
set(x, y, -1 if white else 0)</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 5,531 ⟶ 6,924:
{{works with|SWI Prolog|6.2.6 by Jan Wielemaker, University of Amsterdam}}
[[File:ant.jpg|thumb|right|Sample output]]
<langsyntaxhighlight lang="prolog">%_______________________________________________________________
% Langtons ant.
:-dynamic
Line 5,563 ⟶ 6,956:
(direction(Row,Col,right), R is Row - 1, !, move(north, R, Col)).
 
go :- retractall(black(_)), move(north,49,49), update_win.</langsyntaxhighlight>
 
=={{header|PureBasic}}==
[[File:PureBasic_Langtons_ant.png|thumb|Sample display of PureBasic solution]]
<langsyntaxhighlight lang="purebasic">#White = $FFFFFF
#Black = 0
#planeHeight = 100
Line 5,621 ⟶ 7,014:
Delay(10) ;control animation speed and avoid hogging CPU
Until quit = 1</langsyntaxhighlight>
Sample output:
<pre>Out of bounds after 11669 steps.</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">
"""Langton's ant implementation."""
from enum import Enum, IntEnum
Line 5,708 ⟶ 7,101:
if __name__ == "__main__":
ant(width=75, height=52, max_nb_steps=12000)
</syntaxhighlight>
</lang>
The output is similar to the basic D version.
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ stack 50 ] is xpos ( --> s )
[ stack 50 ] is ypos ( --> s )
 
[ xpos share 0 100 within
ypos share 0 100 within
and ] is inside ( --> b )
 
[ -1 ypos ] is north ( --> n s )
[ 1 xpos ] is east ( --> n s )
[ 1 ypos ] is south ( --> n s )
[ -1 xpos ] is west ( --> n s )
 
[ stack 0 ] is heading ( --> s )
 
[ 1 ] is right ( --> n )
[ -1 ] is left ( --> n )
 
[ heading take
+ 4 mod
heading put ] is turn ( --> )
 
[ heading share
[ table
north east south west ]
do tally ] is move ( --> )
 
[ ypos share peek
xpos share bit & 0 > ] is black? ( [ --> b )
 
[ ypos share
2dup peek
xpos share bit ~ &
unrot poke ] is white ( [ --> [ )
 
[ ypos share
2dup peek
xpos share bit |
unrot poke ] is black ( [ --> [ )
 
[ 50 xpos replace
50 ypos replace
0 heading replace ] is reset ( --> )
 
[ witheach
[ 100 times
[ dup i^ bit &
iff say "[]"
else say " " ]
cr
drop ] ] is draw ( [ --> )
 
[ reset
0 100 of
[ inside while
dup black? iff
[ white left ]
else
[ black right ]
turn
move
again ]
draw ] is ant ( --> )</syntaxhighlight>
 
{{out}}
 
Surplus whitespace trimmed. Shown at <sup>'''2'''</sup>/<sub>'''3'''</sub> size.
 
<pre style="font-size:67%">
[][] [][][][][][][][][][][][] [][]
[] [][][][] [] [][]
[][][] [][] [][] []
[] [] [] [] [] []
[][] [][] [] [] [][][] []
[][][] [] [] [] [] [][] [][] [][][]
[] [] [][][] [][] [][][][] [][] [] [] [] [][] [][]
[] [][][] [][] [] [][] [][][] [] [] [][][] [][][]
[] [] [][][][][] [] [] [][][][] [] [][][] [] [] []
[][][] [][] [] [][][][] [][] [][] [][][][][][] [] [][][] [] []
[] [][][] [] [][] [] [] [][] [][] [][] [] [][][][][] [][][] [][]
[] [] [] [][] [][][] [] [] [] [][][][] [] [][]
[] [] [][] [][] [] [][] [][] [] [][]
[][][] [] [] [][] [][][] [] [][] [] [][][] [][] [][] []
[] [][][] [][] [][] [][] [][][] [] [] [][] [][][][] []
[][][] [] [] [] [] [] [][][][] [][] [] [][] [][][] [] []
[] [][][] [] [][] [] [] [][][] [] [][][] [][] [] [] [][]
[][][] [] [] [][] [] [][] [][] [][][][][] [][][][] [][][][] [][] []
[] [][][] [] [] [] [] [][][] [] [] [][] [][] [] [] [] [] []
[][][] [] [][] [][][] [][] [] [][] [][][][] [][][][] [] []
[] [][][] [] [] [] [][] [][][][][][][][][][][] [] [][][][] [] [] []
[][][] [] [][] [] [][][][] [][] [][][][][][][][][] [] [][] [] [][]
[] [][][] [] [] [][] [] [][] [][] [][] [][][] [][][] [] [] [][] [][][][] []
[][][] [] [][] [] [] [][][][][][] [][] [] [][] [] [] [][][] [][][] [][] []
[] [][][] [] [] [] [][][][][] [] [][][][][] [] [] [][] [] [][] []
[][][] [] [][] [] [] [][] [][][][][] [][] [] [] [] [] [][] [] [] []
[] [][][] [] [] [] [] [][][][] [] [][][][][] [][] [][][][][][][][][][] [][]
[][][] [] [][] [] [][] [][] [] [] [][][][] [] [][] [][][][] [][]
[] [][][] [] [] [][][][][] [] [][] [][] [] [] [] [] [] [] [] []
[][][] [] [][] [][] [][] [] [] [] [][] [][] [] [] [][] [] [][] [][]
[] [][][] [] [] [] [] [] [][][][][][][][] [] [] [][] [][][][] []
[][][] [] [][] [] [] [] [][] [][] [] [] [][] []
[] [][][] [] [] [] [] [] [] [][] [][] [][] [][][][]
[][][] [] [][] [][] [] [][] [][] [] [] [][][]
[] [][][] [] [] [] [][] [][][][] [][][][] [][][] [][][][]
[][][] [] [][] [][] [][][][] [][] [] [][] [] [] []
[] [][][] [] [] [][] [][] [][] [][][] [][] [][][][][]
[][][] [] [][] [] [][] [] [][][][]
[] [][][] [] [] [][] [][] [][]
[][][] [] [][] [][]
[] [][][] [] [] [] [][] [][][][] []
[][][] [] [][] [] [] [][][] [][][]
[] [][][] [] [] [] [][] [] [] []
[][][] [] [][] [][] [][]
[] [][][] [] [] [][]
[][][] [] [][]
[] [] [] [] []
[][][][] [][]
[] [][] []
[][][][]
[][]</pre>
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
langton.ant = function(n = 100) {
map = matrix(data = 0, nrow = n, ncol = n)
Line 5,733 ⟶ 7,248:
 
image(langton.ant(), xaxt = "n", yaxt = "n", bty = "n")
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 5,740 ⟶ 7,255:
This Racket program attempts to avoid mutation.
 
<langsyntaxhighlight lang="racket">#lang racket
 
;; contracts allow us to describe expected behaviour of funcitons
Line 5,803 ⟶ 7,318:
((#t) (place-image (circle 2 "solid" "black") (* x 4) (* y 4) scn)))))
(show-grid/png (langton (make-ant 'u 50 50) (hash)))
</syntaxhighlight>
</lang>
Output (text):
<pre style="height:60ex;overflow:scroll">
Line 5,864 ⟶ 7,379:
{{trans|Perl}}
In this version we use 4-bits-per-char graphics to shrink the output to a quarter the area of ASCII graphics.
<syntaxhighlight lang="raku" perl6line>constant @vecs = [1,0,1], [0,-1,1], [-1,0,1], [0,1,1];
constant @blocky = ' ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█'.comb;
constant $size = 100;
Line 5,888 ⟶ 7,403:
+ 8 * @plane[$x+1][$y+1] ];
}
}</langsyntaxhighlight>
{{out}}
<pre>Out of bounds after 11669 moves at (-1, 26)
Line 5,938 ⟶ 7,453:
<br>the screen to display the maximum area of the ant's path (walk).
<br>Or in other words, this REXX program only shows the pertinent part of the ant's walk─field.
<langsyntaxhighlight lang="rexx">/*REXX program implements Langton's ant walk and displays the ant's path (finite field).*/
parse arg dir char seed . /*obtain optional arguments from the CL*/
if datatype(seed, 'W') then call random ,,seed /*Integer? Then use it as a RANDOM SEED*/
if dir=='' | dir=="," then dir= random(1, 4) /*ant is facing a random direction, */
if char=='' | char=="," then char= '#' /*binary colors: 0≡white, 1≡black. */
parse value scrSize() with sd sw . /*obtain the terminal's depth and width*/
sd= sd -6; sw= sw -1 /*adjust for terminal's useable " useble area. */
xHome= 1000000; yHome=1000000 1000000 /*initially in the middle of nowhere. */
x= xHome; y= yHome /*start ant's walk in middle of nowhere*/
$.= 1; ; $.0= 4 ; $.2= 2 ; $.3= 3; $.4= 4 /* 1≡north 2≡east 3≡south 4≡west.*/
minX= x; minY= y; maxX= x; maxY=y y /*initialize the min/max values for X,Y*/
@.=0 0 /*the universe (walk field) is white.*/
do #=1 until (maxX-minY>sw)|(maxY-minY>sd) /*is the path out─of─bounds for screen?*/
black= @.x.y; @.x.y= \@.x.y /*invert (flip) ant's cell color code.*/
if black then dir= dir - 1 /*if cell color was black, turn left.*/
else dir= dir + 1 /* " " " " white, turn right.*/
dir= $.dir /*$ array handles/adjusts under & over.*/
select /*ant walks the direction it's facing. */
when dir==1 then y= y + 1 /*is ant walking north? Then go up. */
Line 5,961 ⟶ 7,476:
when dir==4 then x= x - 1 /* " " " west? " " left. */
end /*select*/ /*the DIRection is always normalized.*/
minX= min(minX, x); maxX= max(maxX, x) /*find the minimum and maximum of X. */
minY= min(minY, y); maxY= max(maxY, y) /* " " " " " " Y. */
end /*steps*/ /* [↑] ant walks hither and thither. */
/*finished walking, it's out─of─boundsout-of-bounds.*/
say center(" Langton's ant walked " # ' steps ', sw, "─")
@.xHome.yHome= '█' /*show the ant's initial starting point*/
@.x.y= '∙' /*show where the ant went out─of─bounds*/
/* [↓] show Langton's ant's trail. */
do y=maxY to minY by -1; _= /*display a single row of cells. */
do x=minX to maxX; _=_ || @.x.y /*build a cell row for the display. */
end /*x*/ /* [↓] strip trailing blanks from line*/
_= strip( translate(_, char, 10), 'T') /*color the cells: black or white. */
if _\=='' then say _ /*display line (strip trailing blanks).*/
end /*y*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
Programing note: &nbsp; the 23<sup>rd</sup> REXX line:
<langsyntaxhighlight lang="rexx"> when dir==4 then x= x - 1 /* " " " west? " " left. */</langsyntaxhighlight>
could've been coded as:
<langsyntaxhighlight lang="rexx"> otherwise x= x - 1 /* " " " west? " " left. */</langsyntaxhighlight>
The terminal's screen size used was &nbsp; '''80'''<small>x</small>'''160'''.
 
Line 6,069 ⟶ 7,584:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "guilib.ring"
load "stdlib.ring"
Line 6,125 ⟶ 7,640:
}
label1 { setpicture(p1) show() }
</syntaxhighlight>
</lang>
 
Output:
Line 6,132 ⟶ 7,647:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Ant
class OutOfBoundsException < StandardError; end
Line 6,221 ⟶ 7,736:
moves = ant.run
puts "out of bounds after #{moves} moves: #{ant.position}"
puts ant</langsyntaxhighlight>
 
{{out}}
Line 6,326 ⟶ 7,841:
....................................................................................................</pre>
'''Simple Version:'''
<langsyntaxhighlight lang="ruby">class Ant
MOVE = [[1,0], [0,1], [-1,0], [0,-1]] # [0]:east, [1]:south, [2]:west, [3]:north
Line 6,352 ⟶ 7,867:
end
 
puts Ant.new(100, 100).to_s</langsyntaxhighlight>
;Output is the same above.
 
=={{header|Run BASIC}}==
 
<langsyntaxhighlight Runbasiclang="runbasic">dim plane(100,100)
x = 50: y = 50: minY = 100
 
Line 6,385 ⟶ 7,900:
next y
render #g
#g "flush""</langsyntaxhighlight>
 
Ouptut (Produces both character and graphic):[[File:Langtons_ant_run_basic.png‎|right|graphic]]
Line 6,472 ⟶ 7,987:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">struct Ant {
x: usize,
y: usize,
Line 6,548 ⟶ 8,063:
println!("{}", string);
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">class Langton(matrix:Array[Array[Char]], ant:Ant) {
import Langton._
val rows=matrix.size
Line 6,593 ⟶ 8,108:
println(l)
}
}</langsyntaxhighlight>
Output:
<pre style="height: 40ex; overflow: scroll">Out of bounds after 11669 moves
Line 6,699 ⟶ 8,214:
=={{header|Scilab}}==
{{works with|Scilab|5.4.1 or above}}
<syntaxhighlight lang="text">grid_size=100; //side length of the square grid
ant_pos=round([grid_size/2 grid_size/2]); //ant's initial position at center of grid
head_direction='W'; //ant's initial direction can be either
Line 6,769 ⟶ 8,284:
end
 
disp(ascii_grid);</langsyntaxhighlight>
{{out}}
<pre style="font-size: 10px">
Line 6,975 ⟶ 8,490:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: direction is new enum UP, RIGHT, DOWN, LEFT end enum;
Line 7,004 ⟶ 8,519:
writeln;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 7,064 ⟶ 8,579:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">define dirs = [[1,0], [0,-1], [-1,0], [0,1]]
define size = 100
 
Line 7,087 ⟶ 8,602:
 
say "Out of bounds after #{moves} moves at (#{x}, #{y})"
plane.map{.map {|square| square == Black ? '#' : '.' }}.each{.join.say}</langsyntaxhighlight>
 
=={{header|Swift}}==
{{trans|C#}}
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
let WIDTH = 100
Line 7,163 ⟶ 8,678:
}
println()
}</langsyntaxhighlight>
{{out}}
Blank lines omitted
Line 7,251 ⟶ 8,766:
{{libheader|Tk}}
[[File:LangtonAnt_Tcl.gif|thumb|Output of Tcl solution of Langton's ant task]]
<langsyntaxhighlight lang="tcl">package require Tk
 
proc step {workarea} {
Line 7,283 ⟶ 8,798:
 
# Produce output in file
antgrid write ant.gif -format gif</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
The variable N counts the generation number.
<langsyntaxhighlight TIlang="ti-83b">PROGRAM:LANT
:ClrDraw
:0→N
Line 7,305 ⟶ 8,820:
:N+1→N
:End
</syntaxhighlight>
</lang>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{works with|Z Shell}}
This uses the terminal dimensions, so shrink the font and make the window big; should be at least 80 lines by 100 columns.
<syntaxhighlight lang="sh">function main {
typeset -i width=$(tput cols)
typeset -i height=$(tput lines)
typeset -a grid
typeset -i i
for (( i=0; i<height; ++i )); do
grid+=("$(printf "%${width}s" ' ')")
done
typeset -i x=$(( width / 2 )) y=$(( height / 2 ))
(( dx=0, dy = 1 - 2*RANDOM%2 ))
if (( RANDOM % 2 )); then
(( dy=0, dx = 1 - 2*RANDOM%2 ))
fi
printf '\e[H';
printf '%s\n' "${grid[@]}"
tput civis
while (( x>=0 && x < width && y >=0 && y< height)); do
(( i=y ))
if [[ -n $ZSH_VERSION ]]; then
(( i += 1 ))
fi
ch=${grid[i]:$x:1}
if [[ $ch == '#' ]]; then
(( t=dx, dx=dy, dy=-t ))
grid[i]=${grid[i]:0:$x}' '${grid[i]:$x+1}
else
(( t=dx, dx=-dy, dy=t ))
grid[i]=${grid[i]:0:$x}'#'${grid[i]:$x+1}
fi
(( x += dx, y += dy ))
tput cup $y 0 && printf '%s' "${grid[i]}"
done
tput cnorm
read line
return
}
 
main "$@"</syntaxhighlight>
{{Out}}
Example final state:
<pre> ## # #
### # #
# ## ##
## ## #
# # # ##
## # ### #
# # ### ##
## # ####
# # ### ##
## # ####
# # ### ##
## # ####
# # ### ##
## # ####
# # ### ##
## # ####
# # ### ##
## # ####
## # # ### ##
## ## ## # ####
# # # ## # # # ### ##
### ### # # ## # ####
# #### ## # # # ### ##
## ## # ####
## ## ## # # ### ##
#### # ## # ## # ####
##### ## ### ## ## ## # # ### ##
# # # ## # ## #### ## ## # ####
#### ### #### #### ## # # # ### ##
### # # ## ## # ## ## # ####
#### ## ## ## # # # # # # ### ##
# ## # # ## ## # # # ## # ####
# #### ## # # ######## # # # # # ### ##
## ## # ## # # ## ## # # # ## ## ## # ####
# # # # # # # # ## ## # ##### # # ### ##
## #### ## # #### # # ## ## # ## # ####
## ########## ## ##### # #### # # # # ### ##
# # # ## # # # # ## ##### ## # # ## # ####
# ## # ## # # ##### # ##### # # # ### ##
# ## ### ### # # ## # ## ###### # # ## # ####
# #### ## # # ### ### ## ## ## # ## # # ### ##
## # ## # ######### ## #### # ## # ####
# # # #### # ########### ## # # # ### ##
# # #### #### ## # ## ### ## # ####
# # # # # ## ## # # ### # # # # ### ##
# ## #### #### ##### ## ## # ## # # ####
## # # ## ### # ### # # ## # ### ##
# # ### ## # ## #### # # # # # ####
# #### ## # # ### ## ## ## ### ##
# ## ## ### # ## # ### ## # # ####
## # ## ## # ## ## # ##
## # #### # # # ### ## # ###
## ### ##### # ## ## ## # # ## ### #
# # ### # ###### ## ## #### # # ###
# # # ### # #### # # ##### # # #
### ### # # ### ## # ## ###
## ## # # # ## #### ## ### # ##
### ## ## # # # # # #
# ### # # ## #
# # # # #
# ## ## # #
## # #### ##
## ############ #
</pre>
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Sub Ant()
Dim TablDatas(1 To 200, 1 To 256) As String, sDir As String, sFile As String, Str As String
Dim ColA As Integer, LigA As Long, ColF As Integer, LigF As Long, i As Long, j As Integer, Num As Long
Dim Top As Boolean, Left As Boolean, Bottom As Boolean, Right As Boolean
'init variables
Select Case Int(Rnd(4) * 4)
Top = True
Case 0: Top = True
Case 1: Right = True
Case 2: Bottom = True
Case 3: Left = True
End Select
LigF = 80
ColF = 50
Line 7,327 ⟶ 8,957:
Next
'directory
sDir = "C:\/Users\yourname\/mjreed/Desktop\/"
'name txt file
sFile = "Langton_Ant.txt"
'start
Dim Dir As String
For i = 1 To 15000
LigA = LigF
ColA = ColF
If LigA = 1 Or ColA = 1 Or ColA = 256 Or LigA = 200 Then GoTo Fin
If TablDatas(LigA, ColA) = " " Then
TablDatas(LigA, ColA) = "#"
Select Case True
Case Top: Top = False: Left = True: LigF = LigA: ColF = ColA - 1
Case Left: Left = False: Bottom = True: LigF = LigA + 1: ColF = ColA
Case Bottom: Bottom = False: Right = True: LigF = LigA: ColF = ColA + 1
Case Right: Right = False: Top = True: LigF = LigA - 1: ColF = ColA
End Select
Else
TablDatas(LigA, ColA) = " "
Select Case True
Case Top: Top = False: Right = True: LigF = LigA: ColF = ColA + 1
Line 7,351 ⟶ 8,975:
Case Bottom: Bottom = False: Left = True: LigF = LigA: ColF = ColA - 1
Case Right: Right = False: Bottom = True: LigF = LigA + 1: ColF = ColA
End Select
Else
TablDatas(LigA, ColA) = " "
Select Case True
Case Top: Top = False: Left = True: LigF = LigA: ColF = ColA - 1
Case Left: Left = False: Bottom = True: LigF = LigA + 1: ColF = ColA
Case Bottom: Bottom = False: Right = True: LigF = LigA: ColF = ColA + 1
Case Right: Right = False: Top = True: LigF = LigA - 1: ColF = ColA
End Select
End If
Next i
Fin:
'result in txt file
Num = FreeFile
Open sDir & sFile For Output As #Num
For i = 1 To UBound(TablDatas, 1)
Str = vbNullString
Line 7,362 ⟶ 8,996:
Str = Str & TablDatas(i, j)
Next j
Print #1Num, Str
Next i
Close #Num
Exit Sub
Fin:
MsgBox "Stop ! The ant is over limits."
End Sub
</syntaxhighlight>
</lang>
{{out}}
Blank lines elided
<pre>
<pre> ## ## ## ############ ##
###### ## # #### #
## ## # # ## ## ###
# # ## # # # # # #
#### ### # # ### # # ## ##
##### # ## ### ## ## # # # # ###
# ## ## # ## ## # # # ## #### ## ### # #
### # ## ### ### # # ### ## # ## ### #
# ## ## # # # # ### # #### # # ##### # #
### # ## # # ### # ###### ## ## #### # ## ###
# ## ## # ## ### ##### # ## ## ## # # ## # ### #
### # ## ## # #### # # # ### ## # # #
# ## ## # ## # ## ## # ## ## # #
### # ## # ## ## ### # ## # ### ## # # ###
# ## ## # # #### ## # # ### ## ## ## ### #
### # ## # # ### ## # ## #### # # # # # ###
# ## ## # ## # # ## ### # ### # # ## # ### #
### # ## # ## #### #### ##### ## ## # ## # # ###
# ## ## # # # # # # ## ## # # ### # # # # ### #
### # ## # # #### #### ## # ## ### ## # ###
# ## ## # # # # #### # ########### ## # # # ### #
### # ## # ## # ######### ## #### # ## # ###
# ## ### # ## # # ### ### ## ## ## # ## # # ### #
### # ## ### ### # # ## # ## ###### # # ## # ###
# # # ## # # ## # # ##### # ##### # # # ### #
### # ## # ## # # # # ## ##### ## # # ## # ###
## ## ####### # ## ##### # #### # # # # ### #
### ## #### ## # #### # # ## ## # ## # ###
# # ## ## # # # # # ## ## # ##### # # ### #
### ## # ## # # ## ## # # # ## ## ## # ###
# #### ## # # ######## # # # # # ### #
# ### # ## ## ## # # # ## # ###
## ## ## # ## ## # # # # # # ### #
### # # ## ## ## # ## ## # ###
## ## ### #### #### ## # # # ### #
# # # ### # ## #### ## ## # ###
##### ## ### ## ## ## # # ### #
#### # ## # # ## ## # ###
## ## ## # ## ## # # # ### #
## ### # ## ## # ###
# #### ## # # ## ## # # # ### #
### ### # # ### # ## ## # ###
# # # ## # # ## ## # # # ### #
## ## ### # ## ## # ###
## # ## ## # # # ### #
### # ## ## # ###
# ## ## # # # ### #
### # ## ## # ###
# ## ## # # # ### #
### # ## ## # ### </pre>
# ## ## #
### # ##
# ## ## # ##
### # ## ##
# ## ## ## #
#### ### # # ###
# # # ## #### #
### # # # # ## #
### # ## # ## # ##
# # ## # # ##
# # # ##### # #
# ##### ## ######
### ## # ## # # # ## # ##
## # ####### # # ### ## #
# # ###### ## # # ## # #
# # # ## # ###### ####### #
# #### ## # #### ## ## # ## #
# #### # # ###### ## ###
# # ## # ### # ## ## ###
####### # ## ## # #
#### ## ## #### ## ## ## # #
# # # ### ## ### # #### #
### ### # # ##### # # #
# # ### #### ## # ## ### ## #
## ## #### #### # # # #
# # ## ### ### ### #
## ## ### #### # ### ## #
## # #### # # # ## ### ## #
#### ## ## #### # # # # ### #
# ## ### # # ## # # # # # #
# # # ## ## # # ### ##
## # # ##### # # # # #
# ## # # ## ## # ### ###
# # # # # # ### ## ## #
### # ##### ###### ### ####### # ##
# # # ##### ## ##### #####
# ## # # # ## ### ###
#### ##### ######### # #
## # # ### # # # ### ###
# # #### ## ### ## ### ## ##
### # ## # ##### # # # ## ###
# ##### # # ## ## # # # #
###### #### ## # # ## # # ##
## # ### ## #### # ###
# # ##### # # ## # # #
## ### ####### # # ##
# # ## ## # ## #
# # #### ### ## #
# ## ### ## ##
##
##
</pre>
 
=={{header|Vim Script}}==
<langsyntaxhighlight lang="vim">" return character under cursor
function! CurrChar()
return matchstr(getline('.'), '\%' . col('.') . 'c.')
Line 7,486 ⟶ 9,170:
endif
endwhile
endfunction</langsyntaxhighlight>
 
=={{header|Whitespace}}==
 
<langsyntaxhighlight Whitespacelang="whitespace">
Line 7,581 ⟶ 9,265:
</langsyntaxhighlight>
 
Following is the pseudo-Assembly from which the above was generated.
 
<langsyntaxhighlight lang="asm">; For easier access, the direction vector is stored at the end of the heap.
push 10003 dup push 100 store
push 1 sub dup push -1 store
Line 7,621 ⟶ 9,305:
 
5: ; Print a newline and jump back to the counter check.
push 10 ochr jump 4</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|D}}
The textual version only.
<syntaxhighlight lang="wren">var width = 75
var height = 52
var maxSteps = 12000
 
var up = 0
var right = 1
var down = 2
var left = 3
var direction = [up, right, down, left]
 
var white = 0
var black = 1
 
var x = (width/2).floor
var y = (height/2).floor
var m = List.filled(height, null)
for (i in 0...height) m[i] = List.filled(width, 0)
var dir = up
var i = 0
while (i < maxSteps && 0 <= x && x < width && 0 <= y && y < height) {
var turn = (m[y][x] == black)
var index = (dir + (turn ? 1 : -1)) & 3
dir = direction[index]
m[y][x] = (m[y][x] == black) ? white : black
if (dir == up) {
y = y - 1
} else if (dir == right) {
x = x - 1
} else if (dir == down) {
y = y + 1
} else {
x = x + 1
}
i = i + 1
}
for (j in 0...height) {
for (k in 0...width) System.write((m[j][k] == white) ? "." : "#")
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
Same as D entry.
</pre>
 
=={{header|XPL0}}==
[[File:AntXPL0.gif|right]]
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int X, Y, Dir;
[SetVid($13); \set 320x200 graphic video mode
Line 7,641 ⟶ 9,373:
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text mode
]</langsyntaxhighlight>
 
=={{header|zkl}}==
Line 7,647 ⟶ 9,379:
{{trans|XPL0}}
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
<langsyntaxhighlight lang="zkl">white:=0xff|ff|ff; black:=0;
w:=h:=100; bitmap:=PPM(w,h,white);
x:=w/2; y:=h/2; dir:=0; // start in middle facing east
Line 7,661 ⟶ 9,393:
}while((0<=x<w) and (0<=y<h));
 
bitmap.write(File("foo.ppm","wb"));</langsyntaxhighlight>
{{out}}
Same as XPL0 (and using their image).
9,485

edits