Percolation/Site percolation: Difference between revisions
Content added Content deleted
m (correct D code to match requirements) |
m (correct C code to match requirements) |
||
Line 20:
=={{header|C}}==
{{trans|D}}
<lang c>#include <stdio.h>
Line 27 ⟶ 26:
#include <string.h>
#include <stdbool.h>
#define N_COLS 15
#define N_ROWS 15
// Probability granularity 0.0, 0.1, ... 1.0
#define N_STEPS
// Simulation tries
#define N_TRIES
typedef unsigned char Cell;
enum { EMPTY_CELL = ' ',
Line 42 ⟶ 41:
VISITED_CELL = '.' };
typedef Cell Grid[N_ROWS][N_COLS];
void initialize(Grid grid, const double probability) {
for (size_t r = 0; r < N_ROWS; r++)
Line 50 ⟶ 49:
}
}
void show(Grid grid) {
char line[N_COLS + 3];
Line 57 ⟶ 56:
line[N_COLS + 1] = '+';
line[N_COLS + 2] = '\0';
printf("%s\n", line);
for (size_t r = 0; r < N_ROWS; r++) {
Line 67 ⟶ 66:
printf("%s\n", line);
}
bool walk(Grid grid, const size_t r, const size_t c) {
const size_t bottom = N_ROWS - 1;
grid[r][c] = VISITED_CELL;
if (r < bottom && grid[r + 1][c] == EMPTY_CELL) { // Down.
if (walk(grid, r + 1, c))
Line 77 ⟶ 76:
} else if (r == bottom)
return true;
if (c && grid[r][c - 1] == EMPTY_CELL) // Left.
if (walk(grid, r, c - 1))
return true;
if (c < N_COLS - 1 && grid[r][c + 1] == EMPTY_CELL) // Right.
if (walk(grid, r, c + 1))
return true;
if (r && grid[r - 1][c] == EMPTY_CELL) // Up.
if (walk(grid, r - 1, c))
return true;
return false;
}
bool percolate(Grid grid) {
const size_t startR = 0;
Line 101 ⟶ 100:
return false;
}
typedef struct {
double prob;
size_t count;
} Counter;
int main() {
const double probability_step = 1.0 / (N_STEPS - 1);
Counter counters[N_STEPS];
for (size_t i = 0; i < N_STEPS; i++)
counters[i] = (Counter){ i * probability_step, 0 };
bool sample_shown = false;
static Grid grid;
srand(time(NULL));
for (size_t i = 0; i < N_STEPS; i++) {
for (size_t t = 0; t < N_TRIES; t++) {
Line 132 ⟶ 131:
}
}
printf("\nFraction of %d tries that percolate through:\n", N_TRIES);
for (size_t i = 0; i < N_STEPS; i++)
printf("%1.
counters[i].count / (double)N_TRIES);
return 0;
}
{{out}}
<pre>Percolating sample (15x15, probability = 0.
+---------------+
|
|###.. # ##
|
|
|##
| ##
|
|...#
|
|
|# ####
| #
| ## #
|
|
+---------------+
Fraction of
0.
0.
0.
0.
0.
0.
0.
0.
0.
0.
1.0
=={{header|D}}==
|