Jump to content

Langton's ant: Difference between revisions

Updated D entry + second D entry
(Updated D entry + second D entry)
Line 737:
A basic textual version.
<lang d>import std.stdio, std.algorithm, std.traits, std.string;
 
enum Direction { up, right, down, left }
enum Color : char { white = '.', black = '#' }
 
void main() {
enum width = 75, height = 52;
enum nsteps = 12_000;
enum Direction { up, right, down, left }
enum Color : char { white = '.', black = '#' }
uint x = width / 2, y = height / 2;
auto M = new Color[][](height, width);
Line 750 ⟶ 749:
for (int i = 0; i < nsteps && x < width && y < height; i++) {
immutable turn = M[y][x] == Color.black;
dir = [EnumMembers!Direction][(dir + (turn ? -1 : -1)) & 3];
M[y][x] = (M[y][x] == Color.black) ? Color.white : Color.black;
final switch(dir) with (Direction) {
case Direction.up: y--; break;
case Direction.right: x++; break;
case Direction.down: y++; break;
case Direction.left: x--; break;
}
}
Line 762 ⟶ 761:
writeln(join(cast(char[][])M, "\n"));
}</lang>
{{out}}
Output:
<pre>...........................................................................
...........................................................................
Line 816 ⟶ 815:
...........................................................................
</pre>
 
==Image Version==
This similar version requires the module from the Grayscale Image Task to generate and save a PGM image.
<lang d>import std.stdio, std.algorithm, std.traits, grayscale_image;
 
void main() {
enum width = 100, height = 100;
enum nSteps = 12_000;
enum Direction { up, right, down, left }
auto M = new Image!Gray(width, height);
M.clear(Gray.white);
uint x = width / 2, y = height / 2;
auto dir = Direction.up;
 
for (int i = 0; i < nSteps && x < width && y < height; i++) {
immutable turn = M[x, y] == Gray.black;
dir = [EnumMembers!Direction][(dir + (turn ? 1 : -1)) & 3];
M[x, y] = (M[x, y] == Gray.black) ? Gray.white : Gray.black;
final switch(dir) with (Direction) {
case up: y--; break;
case right: x--; break;
case down: y++; break;
case left: x++; break;
}
}
 
M.savePGM("langton_ant.pgm");
}</lang>
 
=={{header|Ela}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.