Conway's Game of Life: Difference between revisions

Added another D version
(→‎{{header|C}}: short console play code)
(Added another D version)
Line 846:
=={{header|D}}==
<lang d>import std.stdio, std.string, std.algorithm, std.typetuple;
 
template SIota(int start, int stop) {
static if (stop <= start)
alias TypeTuple!() SIota;
else
alias TypeTuple!(SIota!(start, stop-1), stop-1) SIota;
 
struct GameOfLife {
Line 865 ⟶ 858:
void opIndexAssign(string[] v, size_t y, size_t x) {
foreach (nr, row; v)
foreach (nc, state; row) {
assert(state == Cell.dead || state == Cell.alive);
grid[y + nr][x + nc] = cast(Cell)state;
}
}
 
Line 875 ⟶ 870:
row[0] = row[$ - 1] = Cell.dead;
 
foreach (nrr; 1 .. grid.length - 1)
foreach (ncc; 1 .. grid[0].length - 1) {
int count = 0;
/*static*/ foreach (i; SIota!(-1, .. 2))
/*static*/ foreach (j; SIota!(-1, .. 2))
static if (i != 0 || j != 0)
count += (grid[nrr + i][ncc + j] == Cell.alive);
auto a = count == 3 ||
(count == 2 && grid[nrr][ncc] == Cell.alive);
newGrid[nrr][ncc] = a ? Cell.alive : Cell.dead;
}
 
Line 897 ⟶ 892:
}
}
 
void main() {
enum glider1 = [" #", "# #", " ##"];
Line 938 ⟶ 932:
| |
-------------------------------------------------------------</pre>
Faster version, same output:
<lang d>import std.stdio, std.string, std.algorithm, std.typetuple;
 
template SIota(int start, int stop) {
static if (stop <= start)
alias TypeTuple!() SIota;
else
alias TypeTuple!(SIota!(start, stop-1), stop-1) SIota;
 
struct GameOfLife {
enum Cell : char { dead = ' ', alive = '#' }
Cell[][] grid, newGrid;
 
this(int x, int y) {
grid = new typeof(grid)(y + 2, x + 2);
newGrid = new typeof(grid)(y + 2, x + 2);
}
 
void opIndexAssign(string[] v, size_t y, size_t x) {
foreach (nr, row; v)
foreach (nc, state; row) {
assert(state == Cell.dead || state == Cell.alive);
grid[y + nr][x + nc] = cast(Cell)state;
}
}
 
void iteration() {
newGrid[0][] = Cell.dead;
newGrid[$ - 1][] = Cell.dead;
foreach (row; newGrid)
row[0] = row[$ - 1] = Cell.dead;
 
foreach (nr; 1 .. grid.length - 1)
foreach (nc; 1 .. grid[0].length - 1) {
int count = 0;
/*static*/ foreach (i; SIota!(-1, 2))
/*static*/ foreach (j; SIota!(-1, 2))
static if (i != 0 || j != 0)
count += (grid[nr + i][nc + j] == Cell.alive);
auto a = count == 3 ||
(count == 2 && grid[nr][nc] == Cell.alive);
newGrid[nr][nc] = a ? Cell.alive : Cell.dead;
}
 
swap(grid, newGrid);
}
 
string toString() {
string ret = "-".repeat(grid[0].length - 1) ~ "\n";
foreach (row; grid[1 .. $-1])
ret ~= "|" ~ cast(char[])row[1 .. $-1] ~ "|\n";
return ret ~ "-".repeat(grid[0].length - 1);
}
}
 
void main() {
enum glider1 = [" #", "# #", " ##"];
enum glider2 = ["# ", "# #", "## "];
 
auto uni = GameOfLife(60, 20);
uni[3, 2] = glider1;
uni[3, 15] = glider2;
uni[3, 19] = glider1;
uni[3, 32] = glider2;
uni[5, 50] = [" # #", "# ", "# #", "#### "];
writeln(uni);
 
foreach (i; 0 .. 20) {
uni.iteration();
writeln(uni);
}
}</lang>
 
=={{header|E}}==
Anonymous user