Jump to content

Maze generation: Difference between revisions

Improved D code
(Updated D code)
(Improved D code)
Line 512:
<lang d>import std.stdio, std.string, std.random, std.algorithm;
 
int[][] makeMaze(constin int heightwidth, constin int widthheight) {
pure static nothrow int[] getCandidateNeighbors(constin int[][] maze, const int i) {
in int i,
in int width,
in int height) {
int[] neighbors;
const int n = i - width;
if (n >= 0 && !maze[n].length)
neighbors ~= n;
const int s = i + width;
if (s < (height * width) && !maze[s].length)
neighbors ~= s;
const int e = i + 1;
if (e >= 0 && e / width == i / width && !maze[e].length)
neighbors ~= e;
const int w = i - 1;
if (w >= 0 && w / width == i / width && !maze[w].length)
neighbors ~= w;
Line 530 ⟶ 533:
}
 
const int totalCells = height * width;
auto maze = new int[][](totalCells);
int currentCell = uniform(0, totalCells);
Line 537 ⟶ 540:
 
while (visited < totalCells) {
int[]const neighbors = getCandidateNeighbors(maze, currentCell);,
width, height);
if (neighbors.length) {
const int ne = neighbors[uniform(0, neighbors.length)];
maze[currentCell] ~= ne;
maze[ne] ~= currentCell;
Line 554 ⟶ 558:
}
 
void showMaze(/*in*/ int[][] maze, constin int heightwidth, constin int widthheight) {
string s1, s2;
foreach (i; 0 .. height * width) {
Line 571 ⟶ 575:
void main() {
enum int height = 8, width = 11;
showMaze(makeMaze(height, width), height), width, height);
}</lang>
Output example:
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.