Langton's ant: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 34:
{{trans|Python}}
<
UP
RIGHT
Line 95:
print_grid(grid)
ant(width' 75, height' 52, max_nb_steps' 12000)</
{{out}}
Line 152:
=={{header|Action!}}==
<
DEFINE DIRE="1"
DEFINE DIRS="2"
Line 223:
DO UNTIL CH#$FF OD
CH=$FF
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Langton's_ant.png Screenshot from Atari 8-bit computer]
=={{header|Ada}}==
<
procedure Langtons_Ant is
Line 284:
Ada.Text_IO.Put_Line("# Iteration:" & Integer'Image(Iteration));
end Langtons_Ant;
</syntaxhighlight>
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]]
<
ant(integer x, y, d, list map)
{
Line 374:
0;
}</
=={{header|ALGOL 68}}==
<
# size of board for Langton's ant #
INT max board = 100;
Line 443:
print( ( board[ r, min col : max col ], newline ) )
OD
END</
{{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)
<
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</
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
Global $iCountMax = 100000
Global $aFields[100][100][2]
Line 638:
Return 1
EndFunc ;==>_SetAnt
</syntaxhighlight>
[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}}==
<
# usage: awk -v debug=0 -f langton.awk
Line 737:
}
END { print("END.") }
</syntaxhighlight>
=={{header|BBC BASIC}}==
<syntaxhighlight 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>
=={{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>).
<
auto i, j
Line 816:
l(100, 100, 50, 50)
quit</
=={{header|Befunge}}==
<
!"$(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</
{{out}}
Line 887:
<code>_while_</code> is an idiom from [https://mlochbaum.github.io/bqncrate/ BQNcrate] which helps with conditional looping.
<
Fmt ← ⊏⟜" #"
_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
Line 904:
}
•Show Fmt Ant ⟨50‿50, 0‿1, 100‿100⥊0⟩</
[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.
<
#include <stdlib.h>
#include <string.h>
Line 984:
walk();
return 0;
}</
=={{header|C sharp|C#}}==
<
namespace LangtonAnt
Line 1,080:
}
}
</syntaxhighlight>
Output:
<pre>
Line 1,169:
If you want to see it running infinitely, set the const bool INFINIT_RUN = true
<
#include <windows.h>
#include <string>
Line 1,468:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
=={{header|Chapel}}==
<
config const gridHeight: int = 100;
config const gridWidth: int = 100;
Line 1,540:
image.writeImage( "output.png" );
}
</syntaxhighlight>
=={{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.
<
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))))))))</
=={{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}}
<
PROGRAM-ID. langtons-ant.
Line 1,652:
WITH BACKGROUND-COLOR White-Background
END-PERFORM
.</
=={{header|CoffeeScript}}==
<
class Ant
constructor: (@world) ->
Line 1,735:
console.log "Ant is at #{ant.location}, direction #{ant.direction}"
world.draw()
</syntaxhighlight>
output
<syntaxhighlight lang="text">
> coffee langstons_ant.coffee
Ant is at -24,46, direction W
Line 1,820:
_____##_________________________________________
______##________________________________________
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(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)))</
=={{header|D}}==
===Textual Version===
<
import std.stdio, std.traits;
Line 1,883:
writefln("%(%-(%c%)\n%)", M);
}</
{{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.
<
void main() {
Line 1,964:
M.savePGM("langton_ant.pgm");
}</
=={{header|Dyalect}}==
<
let yInc = [-1, 0, 0, 1]
let north = 0
Line 2,043:
}
run()</
{{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</
=={{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.
<
(lib 'plot)
(lib 'types)
Line 2,221:
(ant) ;; run
</syntaxhighlight>
=={{header|Ela}}==
Line 2,227:
A straightforward implementation (assumes that we start with ant looking forward):
<
type Field = Field a
Line 2,277:
left Bwd = Rgt
left Rgt = Fwd
left Fwd = Lft</
This implementation is pure (doesn't produce side effects).
Line 2,283:
Testing:
<
Output (empty lines are skipped to save space):
Line 2,343:
{{works with|Elixir|1.1+}}
{{trans|Ruby}}
<
def ant(sizex, sizey) do
{px, py} = {div(sizex,2), div(sizey,2)} # start position
Line 2,369:
end
Langtons.ant(100, 100)</
{{out}}
Line 2,478:
=={{header|Elm}}==
<
import Matrix
import Time exposing (Time, every, second)
Line 2,609:
, update = update
, subscriptions = subscriptions
}</
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">
-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>
{{out}}
Line 2,815:
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.3, 4.0.0 RC1 and later}}
<
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..'</
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 :<
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</
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#}}==
<
// Langton's ant F# https://rosettacode.org/wiki/Langton%27s_ant
Line 2,955:
0
</syntaxhighlight>
<pre>
Line 3,015:
=={{header|Fantom}}==
<
class World
{
Line 3,146:
}
}
</syntaxhighlight>
Output (snipping the blank lines):
Line 3,207:
{{works with|GNU Forth|0.7.0}}
All array manipulations were taken from Rosetta Code examples.
<
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
</
{{out}}
<pre style="height:60ex;overflow:scroll">
Line 3,361:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 3,408:
write(*,*)
end do
end program</
{{out}} (Cropped to save space)
<pre style="height:60ex;overflow:scroll">
Line 3,468:
===But, if one remembers complex numbers===
<syntaxhighlight 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>
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}}==
<
' compile with: fbc -s gui
Line 3,668:
'Print : Print "hit any key to end program"
Sleep
End</
=={{header|Furor}}==
<syntaxhighlight lang="furor">
###sysinclude X.uh
$ff0000 sto szin1
Line 3,723:
{ „direction” }
</syntaxhighlight>
=={{header|Gambas}}==
<
hGridView As GridView 'The display is on a GridView
Line 3,801:
End With
End</
'''[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.
<
'
' Langton's ant
Line 3,902:
WEND
RETURN
</syntaxhighlight>
=={{header|Go}}==
[[file:GoAnt.png|right|thumb|Output png]]
<
import (
Line 3,958:
fmt.Println(err)
}
}</
=={{header|Haskell}}==
Line 3,965:
Necessary import:
<
In order to express the ant's algorithm literally we define two operators:
<
(>>>) = flip (.)
-- functional choice
p ?>> (f, g) = \x -> if p x then f x else g x</
Finally define the datatype representing the state of ant and ant's universe
<
, antDirection :: Point
, getCells :: Set Point }
type Point = (Float, Float)</
Now we are ready to express the main part of the algorithm
<
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</
That's it.
Here is the solution of the task:
<
task = iterate step
>>> dropWhile ((< 50) . distance . antPosition)
>>> getCells . head
where distance (x,y) = max (abs x) (abs y)</
For given initial configuration it returns the set of black cells at the end of iterations.
We can display it graphically using Gloss library
<
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</
Or animate the ant's trajectory
<
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</
=={{header|Icon}} and {{header|Unicon}}==
[[file:LangtonsAnt_unicon_100x100_11655.gif|right|thumb]]
<
procedure main(A)
Line 4,076:
WAttrib(label)
WDone()
end</
{{libheader|Icon Programming Library}}
Line 4,084:
=={{header|J}}==
<
langton=:3 :0
loc=. <.-:$cells=. (_2{.y,y)$dir=. 0
Line 4,094:
end.
' #' {~ cells
)</
<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.
<
import java.awt.Graphics;
Line 4,267:
return plane;
}
}</
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">
// create global canvas
var canvas = document.createElement('canvas');
Line 4,378:
simulate();
}
</syntaxhighlight>
Usage: default ants, custom opts
<syntaxhighlight lang="javascript">
langtonant({}, {
gridsize: 100,
Line 4,388:
interval: 4
});
</syntaxhighlight>
{{out}}
Line 4,398:
Usage: custom ants, default opts
<syntaxhighlight lang="javascript">
langtonant([
{
Line 4,418:
}
]);
</syntaxhighlight>
{{out}}
Line 4,430:
Requires lodash. Wants a canvas with id = "c"
<
///////////////////
// LODASH IMPORT //
Line 4,499:
updateWorld(world, ant, RUNS);
</syntaxhighlight>
=={{header|jq}}==
In the following, the grid is boolean, and white is represented by true.
<syntaxhighlight lang="jq">
def matrix(m; n; init):
if m == 0 then [range(0;n)] | map(init)
Line 4,561:
;
langtons_ant(100)</
{{Out}}
The output is the same as for [[#Rexx|Rexx]] below.
Line 4,567:
=={{header|Julia}}==
{{works with|Julia|1.0}}
<syntaxhighlight lang="julia">
function ant(width, height)
y, x = fld(height, 2), fld(width, 2)
Line 4,586:
ant(100, 100)
</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|D}}
<
enum class Direction { UP, RIGHT, DOWN, LEFT }
Line 4,623:
println()
}
}</
{{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">
.orig x3000
Line 5,353:
.end
</syntaxhighlight>
=={{header|Liberty BASIC}}==
Native graphics.
[[Image:langtonsant.png]]
<
black=0
white=not(black)
Line 5,413:
end
end sub
</
Text version.
<syntaxhighlight lang="lb">
'move up=1 right=2 down=3 left=4
' ---------------------------------
Line 5,445:
next x
</
=={{header|Locomotive Basic}}==
<
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</
Output:
Line 5,469:
=={{header|Logo}}==
<
make "white 1
make "black 2
Line 5,519:
]
]
bye</
{{Output}}
Line 5,577:
=={{header|LOLCODE}}==
<
I HAS A plane ITZ A BUKKIT
Line 5,615:
IM OUTTA YR printer BTW, UR OUTTA CYAN
KTHXBYE</
=={{header|Lua}}==
For this example, the lua Socket and Curses modules and a terminal with enough lines are needed.
<
local curses = require 'curses' -- used for graphics
Line 5,726:
socket.sleep(naptime)
until false
</syntaxhighlight>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Ant {
Form 120,102
Line 5,786:
}
Ant
</syntaxhighlight>
{{out}}
Line 5,877:
[[File:LangtonsAnt.png|right|thumb|Output]]
<
data = SparseArray[{{50, 50} -> -1}, {100, 100}, 1];
NestWhile[
{Re@#, Im@#} &@(direction *= (data[[Sequence @@ #]] *= -1) I) + # &,
{50, 50}, 1 <= Min@# <= Max@# <= 100 &];
Image@data</
=={{header|MATLAB}} / {{header|Octave}}==
<
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</
=={{header|Nim}}==
{{trans|Python}}
<
type
Line 5,942:
for row in m:
echo map(row, proc(x: Color): string =
if x == white: "." else: "#").join("")</
=={{header|OCaml}}==
<
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</
Run with:
Line 5,983:
=={{header|Octave}}==
<
E=100 % Size of lattice.
N=11200 % Number of iterations.
Line 5,994:
endfor;
imagesc(reshape(z,E,E)) % Draw the Lattice
</syntaxhighlight>
=={{header|Ol}}==
{{libheader|OpenGL}}
<
#!/usr/bin/ol
(import (otus random!))
Line 6,070:
)))
</syntaxhighlight>
=={{header|PARI/GP}}==
[[File:Langton-pari.png|right|thumb]]
<
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())</
=={{header|Pascal}}==
Line 6,098:
{{works with|Turbo Pascal}} Except, the green arrow on step 4 does not appear!
<syntaxhighlight lang="pascal">
{$B- Early and safe resolution of If x <> 0 and 1/x...}
Program LangtonsAnt; Uses CRT;
Line 6,212:
END.
</syntaxhighlight>
=={{header|Perl}}==
<
use strict;
# Perl 5 implementation of Langton's Ant
Line 6,255:
}
print "\n";
}</
=={{header|Phix}}==
<!--<
<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>
<!--</
{{out}}
<pre style="font-size: 2px">
Line 6,338:
''to the halves of width and height.)''<br>
<br>
<
// INIT AND DEFINITION
define('dest_name', 'output.png'); // destination image
Line 6,390:
// SAVE IMAGE
imagepng($img, dest_name);
</syntaxhighlight>
=={{header|PicoLisp}}==
[[File:Picolisp_ant.gif|right|thumb]]
This code pipes a PBM into ImageMagick's "display" to show the result:
<
(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>
=={{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">
$Size = 100
Line 6,445:
# Convert to strings for output
ForEach ( $Row in $G ) { ( $Row | ForEach { ( ' ', '', '#')[$_+1] } ) -join '' }
</syntaxhighlight>
{{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.
<
* 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);
}</
==={{header|Processing Python mode}}===
<
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)</
=={{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]]
<
% 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.</
=={{header|PureBasic}}==
[[File:PureBasic_Langtons_ant.png|thumb|Sample display of PureBasic solution]]
<
#Black = 0
#planeHeight = 100
Line 6,751:
Delay(10) ;control animation speed and avoid hogging CPU
Until quit = 1</
Sample output:
<pre>Out of bounds after 11669 steps.</pre>
=={{header|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>
The output is similar to the basic D version.
=={{header|R}}==
<syntaxhighlight 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>
=={{header|Racket}}==
Line 6,870:
This Racket program attempts to avoid mutation.
<
;; 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>
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"
constant @blocky = ' ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█'.comb;
constant $size = 100;
Line 7,018:
+ 8 * @plane[$x+1][$y+1] ];
}
}</
{{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.
<
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. */</
Programing note: the 23<sup>rd</sup> REXX line:
<
could've been coded as:
<
The terminal's screen size used was '''80'''<small>x</small>'''160'''.
Line 7,199:
=={{header|Ring}}==
<
load "guilib.ring"
load "stdlib.ring"
Line 7,255:
}
label1 { setpicture(p1) show() }
</syntaxhighlight>
Output:
Line 7,262:
=={{header|Ruby}}==
<
class OutOfBoundsException < StandardError; end
Line 7,351:
moves = ant.run
puts "out of bounds after #{moves} moves: #{ant.position}"
puts ant</
{{out}}
Line 7,456:
....................................................................................................</pre>
'''Simple Version:'''
<
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</
;Output is the same above.
=={{header|Run BASIC}}==
<
x = 50: y = 50: minY = 100
Line 7,515:
next y
render #g
#g "flush""</
Ouptut (Produces both character and graphic):[[File:Langtons_ant_run_basic.png|right|graphic]]
Line 7,602:
=={{header|Rust}}==
<
x: usize,
y: usize,
Line 7,678:
println!("{}", string);
}
}</
=={{header|Scala}}==
<
import Langton._
val rows=matrix.size
Line 7,723:
println(l)
}
}</
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);</
{{out}}
<pre style="font-size: 10px">
Line 8,105:
=={{header|Seed7}}==
<
const type: direction is new enum UP, RIGHT, DOWN, LEFT end enum;
Line 8,134:
writeln;
end for;
end func;</
{{out}}
Line 8,194:
=={{header|Sidef}}==
{{trans|Raku}}
<
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}</
=={{header|Swift}}==
{{trans|C#}}
<
let WIDTH = 100
Line 8,293:
}
println()
}</
{{out}}
Blank lines omitted
Line 8,381:
{{libheader|Tk}}
[[File:LangtonAnt_Tcl.gif|thumb|Output of Tcl solution of Langton's ant task]]
<
proc step {workarea} {
Line 8,413:
# Produce output in file
antgrid write ant.gif -format gif</
=={{header|TI-83 BASIC}}==
The variable N counts the generation number.
<
:ClrDraw
:0→N
Line 8,435:
:N+1→N
:End
</syntaxhighlight>
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 8,499:
MsgBox "Stop ! The ant is over limits."
End Sub
</syntaxhighlight>
{{out}}
<pre>
Line 8,554:
=={{header|Vim Script}}==
<
function! CurrChar()
return matchstr(getline('.'), '\%' . col('.') . 'c.')
Line 8,616:
endif
endwhile
endfunction</
=={{header|Whitespace}}==
<
Line 8,711:
</
Following is the pseudo-Assembly from which the above was generated.
<
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</
=={{header|Wren}}==
{{trans|D}}
The textual version only.
<
var height = 52
var maxSteps = 12000
Line 8,794:
for (k in 0...width) System.write((m[j][k] == white) ? "." : "#")
System.print()
}</
{{out}}
Line 8,803:
=={{header|XPL0}}==
[[File:AntXPL0.gif|right]]
<
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
]</
=={{header|zkl}}==
Line 8,825:
{{trans|XPL0}}
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
<
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"));</
{{out}}
Same as XPL0 (and using their image).
|