Percolation/Site percolation: Difference between revisions
Content deleted Content added
→{{header|D}}: Marked incomplete |
m correct D code to match requirements |
||
Line 214:
=={{header|D}}==
{{trans|Python}}
<lang d>import std.stdio, std.random, std.array, std.datetime;
enum size_t nCols = 15,
nRows = 15,
nSteps =
nTries =
alias BaseType = char;
enum Cell : BaseType { empty = ' ',
Line 229 ⟶ 227:
visited = '.' }
alias Grid = Cell[nCols][nRows];
void initialize(ref Grid grid, in double probability,
ref Xorshift rng) {
Line 239 ⟶ 237:
}
}
void show(in ref Grid grid) {
immutable static line = '+' ~ "-".replicate(nCols) ~ "+";
Line 247 ⟶ 245:
line.writeln;
}
bool percolate(ref Grid grid) pure nothrow {
bool walk(in size_t r, in size_t c) nothrow {
enum bottom = nRows - 1;
grid[r][c] = Cell.visited;
if (r < bottom && grid[r + 1][c] == Cell.empty) { // Down.
if (walk(r + 1, c))
Line 258 ⟶ 256:
} else if (r == bottom)
return true;
if (c && grid[r][c - 1] == Cell.empty) // Left.
if (walk(r, c - 1))
return true;
if (c < nCols - 1 && grid[r][c + 1] == Cell.empty) // Right.
if (walk(r, c + 1))
return true;
if (r && grid[r - 1][c] == Cell.empty) // Up.
if (walk(r - 1, c))
return true;
return false;
}
enum startR = 0;
foreach (immutable c; 0 .. nCols)
Line 281 ⟶ 279:
return false;
}
void main() {
static struct Counter {
Line 287 ⟶ 285:
size_t count;
}
StopWatch sw;
sw.start;
enum probabilityStep = 1.0 / (nSteps - 1);
Counter[nSteps] counters;
foreach (immutable i, ref co; counters)
co.prob = i * probabilityStep;
Grid grid;
bool sampleShown = false;
auto rng = Xorshift(unpredictableSeed);
foreach (ref co; counters) {
foreach (immutable _; 0 .. nTries) {
Line 316 ⟶ 314:
}
sw.stop;
writefln("\nFraction of %d tries that percolate through:", nTries);
foreach (const co; counters)
writefln("%1.
writefln("\nSimulations and grid printing performed" ~
" in %
}</lang>
{{out}}
<pre>Percolating sample (15x15, probability = 0.
+---------------+
|.
|
|#
|#
|
|
|#
|##.#
|
|
|
|
| ####
| # ##
| ## #
+---------------+
Fraction of
0.
0.
0.
0.
0.
0.
0.
0.
0.
0.
1.0
Simulations and grid printing performed in
</pre>
=={{header|Python}}==
|