Langton's ant: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 34:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">T.enum Dir
UP
RIGHT
Line 95:
print_grid(grid)
 
ant(width' 75, height' 52, max_nb_steps' 12000)</langsyntaxhighlight>
 
{{out}}
Line 152:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE DIRN="0"
DEFINE DIRE="1"
DEFINE DIRS="2"
Line 223:
DO UNTIL CH#$FF OD
CH=$FF
RETURN</langsyntaxhighlight>
{{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 284:
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 342:
=={{header|Aime}}==
[[File:ant_phpoFTAAk.png|100px|Output png]]
<langsyntaxhighlight lang="aime">void
ant(integer x, y, d, list map)
{
Line 374:
 
0;
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
# size of board for Langton's ant #
INT max board = 100;
Line 443:
print( ( board[ r, min col : max col ], newline ) )
OD
END</langsyntaxhighlight>
{{out}}
<pre>
Line 503:
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 558:
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 638:
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 737:
}
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 762:
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 816:
 
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 887:
<code>_while_</code> is an idiom from [https://mlochbaum.github.io/bqncrate/ BQNcrate] which helps with conditional looping.
 
<langsyntaxhighlight lang="bqn">Rot ← ¬⊸{-⌾(𝕨⊸⊑)⌽𝕩}
Fmt ← ⊏⟜" #"
_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
Line 904:
}
 
•Show Fmt Ant ⟨50‿50, 0‿1, 100‿100⥊0⟩</langsyntaxhighlight>
 
[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)
Line 910:
=={{header|C}}==
Requires ANSI terminal.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 984:
walk();
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
namespace LangtonAnt
Line 1,080:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,169:
 
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,468:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
 
=={{header|Chapel}}==
<langsyntaxhighlight lang="chapel">
config const gridHeight: int = 100;
config const gridWidth: int = 100;
Line 1,540:
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,557:
(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,652:
WITH BACKGROUND-COLOR White-Background
END-PERFORM
.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
class Ant
constructor: (@world) ->
Line 1,735:
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,820:
_____##_________________________________________
______##________________________________________
</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,854:
 
(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,883:
 
writefln("%(%-(%c%)\n%)", M);
}</langsyntaxhighlight>
{{out}}
<pre>...........................................................................
Line 1,940:
===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,964:
 
M.savePGM("langton_ant.pgm");
}</langsyntaxhighlight>
 
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang="dyalect">let xInc = [0, 1, -1, 0]
let yInc = [-1, 0, 0, 1]
let north = 0
Line 2,043:
}
run()</langsyntaxhighlight>
 
{{out}}
Line 2,134:
[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">len f[] 100 * 100
func show . .
for y range 100
Line 2,157:
.
call run 70 40 0
call show</langsyntaxhighlight>
 
=={{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 2,221:
 
(ant) ;; run
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
Line 2,227:
A straightforward implementation (assumes that we start with ant looking forward):
 
<langsyntaxhighlight lang="ela">open list core generic
type Field = Field a
Line 2,277:
left Bwd = Rgt
left Rgt = Fwd
left Fwd = Lft</langsyntaxhighlight>
 
This implementation is pure (doesn't produce side effects).
Line 2,283:
Testing:
 
<langsyntaxhighlight lang="ela">showPath <| move 100 50 50</langsyntaxhighlight>
 
Output (empty lines are skipped to save space):
Line 2,343:
{{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,369:
end
 
Langtons.ant(100, 100)</langsyntaxhighlight>
 
{{out}}
Line 2,478:
 
=={{header|Elm}}==
<langsyntaxhighlight lang="elm">import Maybe as M
import Matrix
import Time exposing (Time, every, second)
Line 2,609:
, update = update
, subscriptions = subscriptions
}</langsyntaxhighlight>
 
Link to live demo: https://dc25.github.io/langtonsAntElm/
Line 2,615:
=={{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,728:
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,815:
=={{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,879:
 
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,893:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Langton's ant F# https://rosettacode.org/wiki/Langton%27s_ant
 
Line 2,955:
0
 
</syntaxhighlight>
</lang>
 
<pre>
Line 3,015:
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class World
{
Line 3,146:
}
}
</syntaxhighlight>
</lang>
 
Output (snipping the blank lines):
Line 3,207:
{{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,274:
: langton.ant run.ant draw.grid ; \ launches the ant, outputs the result
 
</langsyntaxhighlight>
{{out}}
<pre style="height:60ex;overflow:scroll">
Line 3,361:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Langtons_Ant
implicit none
 
Line 3,408:
write(*,*)
end do
end program</langsyntaxhighlight>
{{out}} (Cropped to save space)
<pre style="height:60ex;overflow:scroll">
Line 3,468:
 
===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,515:
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,604:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 16-10-2016
' compile with: fbc -s gui
 
Line 3,668:
'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,723:
{ „direction” }
 
</syntaxhighlight>
</lang>
 
=={{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,801:
End With
 
End</langsyntaxhighlight>
'''[http://www.cogier.com/gambas/Langton's%20ant.png Click here for an image of the result]'''
 
Line 3,808:
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,902:
WEND
RETURN
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
[[file:GoAnt.png|right|thumb|Output png]]
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,958:
fmt.Println(err)
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 3,965:
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,992:
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 4,013:
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 4,076:
WAttrib(label)
WDone()
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 4,084:
=={{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 4,094:
end.
' #' {~ cells
)</langsyntaxhighlight>
 
<pre style="font-size: 2px"> langton 100 100
Line 4,200:
=={{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,267:
return plane;
}
}</langsyntaxhighlight>
Output (click for a larger view):
 
Line 4,276:
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,378:
simulate();
}
</syntaxhighlight>
</lang>
 
Usage: default ants, custom opts
 
<syntaxhighlight lang="javascript">
<lang JavaScript>
langtonant({}, {
gridsize: 100,
Line 4,388:
interval: 4
});
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,398:
Usage: custom ants, default opts
 
<syntaxhighlight lang="javascript">
<lang JavaScript>
langtonant([
{
Line 4,418:
}
]);
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,430:
Requires lodash. Wants a canvas with id = "c"
 
<langsyntaxhighlight lang="javascript">
///////////////////
// LODASH IMPORT //
Line 4,499:
 
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,561:
;
langtons_ant(100)</langsyntaxhighlight>
{{Out}}
The output is the same as for [[#Rexx|Rexx]] below.
Line 4,567:
=={{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,586:
 
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,623:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,635:
"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,353:
 
.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,413:
end
end sub
</langsyntaxhighlight>
 
Text version.
<syntaxhighlight lang="lb">
<lang lb>
'move up=1 right=2 down=3 left=4
' ---------------------------------
Line 5,445:
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,462:
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,469:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">make "size 100
make "white 1
make "black 2
Line 5,519:
]
]
bye</langsyntaxhighlight>
 
{{Output}}
Line 5,577:
=={{header|LOLCODE}}==
 
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.3
 
I HAS A plane ITZ A BUKKIT
Line 5,615:
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,726:
socket.sleep(naptime)
until false
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Ant {
Form 120,102
Line 5,786:
}
Ant
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,877:
[[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,905:
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,942:
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,977:
if not(key_pressed()) then loop (move pos dir) dir
in
loop (size_x()/2, size_y()/2) North</langsyntaxhighlight>
 
Run with:
Line 5,983:
 
=={{header|Octave}}==
<langsyntaxhighlight OCTAVElang="octave">clear
E=100 % Size of lattice.
N=11200 % Number of iterations.
Line 5,994:
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 6,070:
 
)))
</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 6,088:
plothraw(u,v)
};
show(langton())</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 6,098:
{{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 6,212:
 
END.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use strict;
# Perl 5 implementation of Langton's Ant
Line 6,255:
}
print "\n";
}</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<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>
Line 6,274:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre style="font-size: 2px">
Line 6,338:
''to the halves of width and height.)''<br>
<br>
<langsyntaxhighlight lang="php">
// INIT AND DEFINITION
define('dest_name', 'output.png'); // destination image
Line 6,390:
// 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,412:
(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,445:
# 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,506:
=={{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,586:
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,655:
 
def setBool(x, y, white):
set(x, y, -1 if white else 0)</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 6,661:
{{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,693:
(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,751:
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,838:
if __name__ == "__main__":
ant(width=75, height=52, max_nb_steps=12000)
</syntaxhighlight>
</lang>
The output is similar to the basic D version.
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
langton.ant = function(n = 100) {
map = matrix(data = 0, nrow = n, ncol = n)
Line 6,863:
 
image(langton.ant(), xaxt = "n", yaxt = "n", bty = "n")
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 6,870:
This Racket program attempts to avoid mutation.
 
<langsyntaxhighlight lang="racket">#lang racket
 
;; contracts allow us to describe expected behaviour of funcitons
Line 6,933:
((#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,994:
{{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 7,018:
+ 8 * @plane[$x+1][$y+1] ];
}
}</langsyntaxhighlight>
{{out}}
<pre>Out of bounds after 11669 moves at (-1, 26)
Line 7,068:
<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 7,104:
_= 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 7,199:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "guilib.ring"
load "stdlib.ring"
Line 7,255:
}
label1 { setpicture(p1) show() }
</syntaxhighlight>
</lang>
 
Output:
Line 7,262:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Ant
class OutOfBoundsException < StandardError; end
Line 7,351:
moves = ant.run
puts "out of bounds after #{moves} moves: #{ant.position}"
puts ant</langsyntaxhighlight>
 
{{out}}
Line 7,456:
....................................................................................................</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,482:
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,515:
next y
render #g
#g "flush""</langsyntaxhighlight>
 
Ouptut (Produces both character and graphic):[[File:Langtons_ant_run_basic.png‎|right|graphic]]
Line 7,602:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">struct Ant {
x: usize,
y: usize,
Line 7,678:
println!("{}", string);
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">class Langton(matrix:Array[Array[Char]], ant:Ant) {
import Langton._
val rows=matrix.size
Line 7,723:
println(l)
}
}</langsyntaxhighlight>
Output:
<pre style="height: 40ex; overflow: scroll">Out of bounds after 11669 moves
Line 7,829:
=={{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,899:
end
 
disp(ascii_grid);</langsyntaxhighlight>
{{out}}
<pre style="font-size: 10px">
Line 8,105:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: direction is new enum UP, RIGHT, DOWN, LEFT end enum;
Line 8,134:
writeln;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 8,194:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">define dirs = [[1,0], [0,-1], [-1,0], [0,1]]
define size = 100
 
Line 8,217:
 
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,293:
}
println()
}</langsyntaxhighlight>
{{out}}
Blank lines omitted
Line 8,381:
{{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,413:
 
# 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,435:
:N+1→N
:End
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 8,499:
MsgBox "Stop ! The ant is over limits."
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 8,554:
 
=={{header|Vim Script}}==
<langsyntaxhighlight lang="vim">" return character under cursor
function! CurrChar()
return matchstr(getline('.'), '\%' . col('.') . 'c.')
Line 8,616:
endif
endwhile
endfunction</langsyntaxhighlight>
 
=={{header|Whitespace}}==
 
<langsyntaxhighlight Whitespacelang="whitespace">
Line 8,711:
</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,751:
 
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.
<langsyntaxhighlight lang="ecmascript">var width = 75
var height = 52
var maxSteps = 12000
Line 8,794:
for (k in 0...width) System.write((m[j][k] == white) ? "." : "#")
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 8,803:
=={{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,819:
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text mode
]</langsyntaxhighlight>
 
=={{header|zkl}}==
Line 8,825:
{{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,839:
}while((0<=x<w) and (0<=y<h));
 
bitmap.write(File("foo.ppm","wb"));</langsyntaxhighlight>
{{out}}
Same as XPL0 (and using their image).
10,327

edits