Langton's ant: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(40 intermediate revisions by 18 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 =
if leftTurn {
leftTurns[ant:.direction]
} else {
rightTurns[ant:.direction]
}
this[ptCur:.x][ptCur:.y] = !this[ptCur:.x][ptCur:.y]
move(ant)
ptCur = (x =: ant:.position:.x + ant:.origin:.x, y =: ant:.position:.y + ant:.origin:.y)
ant:.outOfBounds =
ptCur:.x < 0 ||
ptCur:.x >= ant:.width ||
ptCur:.y < 0 ||
ptCur:.y >= ant:.height
ant:.position
}
func newAnt(width, height) {
(
var position =: (var x =: 0, yvar =y: 0),
var origin =: (x =: width / 2, y =: height / 2),
outOfBoundsvar =outOfBounds: false,
isBlackvar =isBlack: [],
directionvar =direction: east,
widthvar =width: width,
heightvar =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)
}
Line 1,819 ⟶ 2,180:
}
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.
Line 2,669 ⟶ 3,032:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Langton's ant F# https://rosettacode.org/wiki/Langton%27s_ant
 
Line 2,731 ⟶ 3,094:
0
 
</syntaxhighlight>
</lang>
 
<pre>
Line 2,791 ⟶ 3,154:
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class World
{
Line 2,922 ⟶ 3,285:
}
}
</syntaxhighlight>
</lang>
 
Output (snipping the blank lines):
Line 2,983 ⟶ 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 3,050 ⟶ 3,413:
: langton.ant run.ant draw.grid ; \ launches the ant, outputs the result
 
</langsyntaxhighlight>
{{out}}
<pre style="height:60ex;overflow:scroll">
Line 3,137 ⟶ 3,500:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Langtons_Ant
implicit none
 
Line 3,184 ⟶ 3,547:
write(*,*)
end do
end program</langsyntaxhighlight>
{{out}} (Cropped to save space)
<pre style="height:60ex;overflow:scroll">
Line 3,244 ⟶ 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,291 ⟶ 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,380 ⟶ 3,743:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 16-10-2016
' compile with: fbc -s gui
 
Line 3,444 ⟶ 3,807:
'Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
 
=={{header|Furor}}==
<syntaxhighlight lang="furor">
<lang Furor>
###sysinclude X.uh
$ff0000 sto szin1
Line 3,499 ⟶ 3,862:
{ „direction” }
 
</syntaxhighlight>
</lang>
 
=={{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,577 ⟶ 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,584 ⟶ 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,678 ⟶ 4,107:
WEND
RETURN
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
[[file:GoAnt.png|right|thumb|Output png]]
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,734 ⟶ 4,163:
fmt.Println(err)
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 3,741 ⟶ 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,768 ⟶ 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,789 ⟶ 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,852 ⟶ 4,281:
WAttrib(label)
WDone()
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 3,860 ⟶ 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,870 ⟶ 4,299:
end.
' #' {~ cells
)</langsyntaxhighlight>
 
<pre style="font-size: 2px"> langton 100 100
Line 3,976 ⟶ 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 4,043 ⟶ 4,472:
return plane;
}
}</langsyntaxhighlight>
Output (click for a larger view):
 
Line 4,052 ⟶ 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 4,154 ⟶ 4,583:
simulate();
}
</syntaxhighlight>
</lang>
 
Usage: default ants, custom opts
 
<syntaxhighlight lang="javascript">
<lang JavaScript>
langtonant({}, {
gridsize: 100,
Line 4,164 ⟶ 4,593:
interval: 4
});
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,174 ⟶ 4,603:
Usage: custom ants, default opts
 
<syntaxhighlight lang="javascript">
<lang JavaScript>
langtonant([
{
Line 4,194 ⟶ 4,623:
}
]);
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,206 ⟶ 4,635:
Requires lodash. Wants a canvas with id = "c"
 
<langsyntaxhighlight lang="javascript">
///////////////////
// LODASH IMPORT //
Line 4,275 ⟶ 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,290 ⟶ 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,337 ⟶ 4,766:
;
langtons_ant(100)</langsyntaxhighlight>
{{Out}}
The output is the same as for [[#Rexx|Rexx]] below.
Line 4,343 ⟶ 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,362 ⟶ 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,399 ⟶ 4,828:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,411 ⟶ 4,840:
"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">
<lang LC-3>
 
.orig x3000
Line 5,129 ⟶ 5,558:
 
.end
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
Native graphics.
[[Image:langtonsant.png]]
<langsyntaxhighlight lang="lb">dim arena(100,100)
black=0
white=not(black)
Line 5,189 ⟶ 5,618:
end
end sub
</langsyntaxhighlight>
 
Text version.
<syntaxhighlight lang="lb">
<lang lb>
'move up=1 right=2 down=3 left=4
' ---------------------------------
Line 5,221 ⟶ 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 5,238 ⟶ 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 5,245 ⟶ 5,674:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">make "size 100
make "white 1
make "black 2
Line 5,295 ⟶ 5,724:
]
]
bye</langsyntaxhighlight>
 
{{Output}}
Line 5,353 ⟶ 5,782:
=={{header|LOLCODE}}==
 
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.3
 
I HAS A plane ITZ A BUKKIT
Line 5,391 ⟶ 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 5,502 ⟶ 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 5,562 ⟶ 5,991:
}
Ant
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,650 ⟶ 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 5,681 ⟶ 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 5,703 ⟶ 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 5,718 ⟶ 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 5,753 ⟶ 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 5,759 ⟶ 6,246:
 
=={{header|Octave}}==
<langsyntaxhighlight OCTAVElang="octave">clear
E=100 % Size of lattice.
N=11200 % Number of iterations.
Line 5,770 ⟶ 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 5,846 ⟶ 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 5,864 ⟶ 6,351:
plothraw(u,v)
};
show(langton())</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 5,874 ⟶ 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,988 ⟶ 6,475:
 
END.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use strict;
# Perl 5 implementation of Langton's Ant
Line 6,031 ⟶ 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 6,112 ⟶ 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 6,164 ⟶ 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 6,186 ⟶ 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 6,219 ⟶ 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 6,280 ⟶ 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 6,360 ⟶ 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 6,429 ⟶ 6,918:
 
def setBool(x, y, white):
set(x, y, -1 if white else 0)</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 6,435 ⟶ 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 6,467 ⟶ 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 6,525 ⟶ 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 6,612 ⟶ 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 6,637 ⟶ 7,248:
 
image(langton.ant(), xaxt = "n", yaxt = "n", bty = "n")
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 6,644 ⟶ 7,255:
This Racket program attempts to avoid mutation.
 
<langsyntaxhighlight lang="racket">#lang racket
 
;; contracts allow us to describe expected behaviour of funcitons
Line 6,707 ⟶ 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 6,768 ⟶ 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 6,792 ⟶ 7,403:
+ 8 * @plane[$x+1][$y+1] ];
}
}</langsyntaxhighlight>
{{out}}
<pre>Out of bounds after 11669 moves at (-1, 26)
Line 6,842 ⟶ 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*/
Line 6,878 ⟶ 7,489:
_= 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,973 ⟶ 7,584:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "guilib.ring"
load "stdlib.ring"
Line 7,029 ⟶ 7,640:
}
label1 { setpicture(p1) show() }
</syntaxhighlight>
</lang>
 
Output:
Line 7,036 ⟶ 7,647:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Ant
class OutOfBoundsException < StandardError; end
Line 7,125 ⟶ 7,736:
moves = ant.run
puts "out of bounds after #{moves} moves: #{ant.position}"
puts ant</langsyntaxhighlight>
 
{{out}}
Line 7,230 ⟶ 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 7,256 ⟶ 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 7,289 ⟶ 7,900:
next y
render #g
#g "flush""</langsyntaxhighlight>
 
Ouptut (Produces both character and graphic):[[File:Langtons_ant_run_basic.png‎|right|graphic]]
Line 7,376 ⟶ 7,987:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">struct Ant {
x: usize,
y: usize,
Line 7,452 ⟶ 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 7,497 ⟶ 8,108:
println(l)
}
}</langsyntaxhighlight>
Output:
<pre style="height: 40ex; overflow: scroll">Out of bounds after 11669 moves
Line 7,603 ⟶ 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 7,673 ⟶ 8,284:
end
 
disp(ascii_grid);</langsyntaxhighlight>
{{out}}
<pre style="font-size: 10px">
Line 7,879 ⟶ 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,908 ⟶ 8,519:
writeln;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 7,968 ⟶ 8,579:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">define dirs = [[1,0], [0,-1], [-1,0], [0,1]]
define size = 100
 
Line 7,991 ⟶ 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 8,067 ⟶ 8,678:
}
println()
}</langsyntaxhighlight>
{{out}}
Blank lines omitted
Line 8,155 ⟶ 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 8,187 ⟶ 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 8,209 ⟶ 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 8,231 ⟶ 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 8,255 ⟶ 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 8,266 ⟶ 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 8,390 ⟶ 9,170:
endif
endwhile
endfunction</langsyntaxhighlight>
 
=={{header|Whitespace}}==
 
<langsyntaxhighlight Whitespacelang="whitespace">
Line 8,485 ⟶ 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 8,525 ⟶ 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 8,545 ⟶ 9,373:
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text mode
]</langsyntaxhighlight>
 
=={{header|zkl}}==
Line 8,551 ⟶ 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 8,565 ⟶ 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,476

edits