Maze generation: Difference between revisions

Improved D version
(Improved D code)
(Improved D version)
Line 512:
<lang d>import std.stdio, std.string, std.random, std.algorithm;
 
int[][] makeMaze(in int width, in int height) {
in {
assert(width > 0 && height > 0);
} out(maze) {
assert(maze.length == width * height);
foreach (el; maze) {
assert(el.length <= 4);
foreach (cc; el)
assert(cc >= 0 && cc < height * width);
}
} body {
pure static nothrow int[] getCandidateNeighbors(in int[][] maze,
in int i,
in int width,
in int height) {
in {
assert(width > 0 && height > 0);
assert(i >= 0 && i < height * width);
assert(maze.length == width * height);
foreach (el; maze) {
assert(el.length <= 4);
foreach (cc; el)
assert(cc >= 0 && cc < height * width);
}
} out(result) {
assert(result.length <= 4);
foreach (cc; result)
assert(cc >= 0 && cc < height * width);
} body {
int[] neighbors;
const int n = i - width;
Line 537 ⟶ 561:
int currentCell = uniform(0, totalCells);
int visited = 1;
int[] cellstackcellStack;
 
while (visited < totalCells) {
assert(currentCell >= 0 && currentCell < (height * width));
const neighbors = getCandidateNeighbors(maze, currentCell,
width, height);
Line 546 ⟶ 571:
maze[currentCell] ~= ne;
maze[ne] ~= currentCell;
cellstackcellStack ~= currentCell;
currentCell = ne;
visited++;
} else {
currentCell = cellstackcellStack[$ - 1];
cellstackcellStack.length -= 1;
}
}
Line 558 ⟶ 583:
}
 
void showMaze(/*in*/ int[][] maze, in int width, in int height) {
in {
assert(width > 0 && height > 0 && maze.length == width * height);
foreach (el; maze) {
assert(el.length <= 4);
foreach (cc; el)
assert(cc >= 0 && cc < height * width);
}
} body {
string s1, s2;
foreach (i; 0 .. heightwidth * widthheight) {
if (i % width == 0) {
writeln(s1);
Anonymous user