Anonymous user
Galton box animation: Difference between revisions
Improved D code
(+ simplified textual D entry) |
(Improved D code) |
||
Line 396:
<lang d>import std.stdio, std.algorithm, std.random, std.array;
enum int boxW = 41, boxH = 37; // Galton box width and height.
enum int
enum int
static assert(boxW >= 2 && boxH >= 2);
static assert((boxW - 4) >= (
static assert((boxH - 3) >=
▲enum center = pegsBaseW + (boxW - (pegsBaseW * 2 - 1)) / 2 - 1;
alias CellBaseType = dchar;▼
enum Cell : CellBaseType { empty = ' ',
ball = 'o',
Line 413 ⟶ 411:
corner = '+',
floor = '-',
Cell[boxW][boxH] box; // Galton box. Will be printed upside-down.
struct Ball {
int x, y; // Position.
this(in int x_, in int y_)
} body {
}
assert(x >= 0 && x < boxW && y >= 0 && y < boxH);
▲ }
}
void
if (
return; // Reached the bottom of the box.
▲ if (box[y - 1][x] == Cell.empty) {
with (Cell)
final switch (box[y -
box[y][x] = Cell.
box[y][x + 1] == Cell.empty) {
x += uniform(0, 2) * 2 - 1;
return;▼
} else if (box[y][x - 1] == Cell.empty)
x++;▼
box[y][x] = Cell.ball;
break;
}
▲ if (box[y][x - 1] == Cell.empty)
▲ x++;
▲ else
▲ x--;
▲ box[y][x] = Cell.ball;
▲ return;
}
▲ assert(0);
}
}
void initializeBox() {
// Set ceiling and floor:
box[0] = Cell.corner ~ [Cell.floor].replicate(boxW - 2)
~ Cell.corner;
box[$ - 1] = box[0][];
// Set walls:
foreach (r; 1 .. boxH - 1)
box[r][0] = box[r][$ - 1] = Cell.wall;
// Set pins:
foreach (nPegs; 1 .. pegsBaseW + 1)▼
box[boxH - 2 -
= Cell.pin;
}
Line 476 ⟶ 485:
foreach_reverse (ref row; box)
writeln(cast(CellBaseType[])row);
Ball[] balls;▼
▲ assert(box[$ - 2][center] == Cell.empty);
▲ box[b.y][b.x] = Cell.ball;
}
void main() {
initializeBox();
▲ Ball[] balls;
foreach (const i; 0 ..
if (i < nBalls)▼
▲ addBall();
writefln("\nStep %d:", i);
balls ~= Ball(centerH, boxH - 2); // Add ball.
drawBox();
// Next step for the simulation.
// Frozen balls are kept in balls array for simplicity.
foreach (ref b; balls)
b.
}
}</lang>
Line 607 ⟶ 611:
| |
| |
| o
| o
| o
| o
| o
| o
| o
| o o o
| o o o
| o o o o
|
|
|
+---------------------------------------+</pre>
|