Maze generation: Difference between revisions
Content added Content deleted
(Updated D code) |
(Improved D code) |
||
Line 512: | Line 512: | ||
<lang d>import std.stdio, std.string, std.random, std.algorithm; |
<lang d>import std.stdio, std.string, std.random, std.algorithm; |
||
int[][] makeMaze( |
int[][] makeMaze(in int width, in int height) { |
||
int[] getCandidateNeighbors( |
pure static nothrow int[] getCandidateNeighbors(in int[][] maze, |
||
in int i, |
|||
in int width, |
|||
in int height) { |
|||
int[] neighbors; |
int[] neighbors; |
||
int n = i - width; |
const int n = i - width; |
||
if (n >= 0 && !maze[n].length) |
if (n >= 0 && !maze[n].length) |
||
neighbors ~= n; |
neighbors ~= n; |
||
int s = i + width; |
const int s = i + width; |
||
if (s < (height * width) && !maze[s].length) |
if (s < (height * width) && !maze[s].length) |
||
neighbors ~= s; |
neighbors ~= s; |
||
int e = i + 1; |
const int e = i + 1; |
||
if (e >= 0 && e / width == i / width && !maze[e].length) |
if (e >= 0 && e / width == i / width && !maze[e].length) |
||
neighbors ~= e; |
neighbors ~= e; |
||
int w = i - 1; |
const int w = i - 1; |
||
if (w >= 0 && w / width == i / width && !maze[w].length) |
if (w >= 0 && w / width == i / width && !maze[w].length) |
||
neighbors ~= w; |
neighbors ~= w; |
||
Line 530: | Line 533: | ||
} |
} |
||
int totalCells = height * width; |
const int totalCells = height * width; |
||
auto maze = new int[][](totalCells); |
auto maze = new int[][](totalCells); |
||
int currentCell = uniform(0, totalCells); |
int currentCell = uniform(0, totalCells); |
||
Line 537: | Line 540: | ||
while (visited < totalCells) { |
while (visited < totalCells) { |
||
const neighbors = getCandidateNeighbors(maze, currentCell, |
|||
width, height); |
|||
if (neighbors.length) { |
if (neighbors.length) { |
||
int ne = neighbors[uniform(0, neighbors.length)]; |
const int ne = neighbors[uniform(0, neighbors.length)]; |
||
maze[currentCell] ~= ne; |
maze[currentCell] ~= ne; |
||
maze[ne] ~= currentCell; |
maze[ne] ~= currentCell; |
||
Line 554: | Line 558: | ||
} |
} |
||
void showMaze(int[][] maze, |
void showMaze(/*in*/ int[][] maze, in int width, in int height) { |
||
string s1, s2; |
string s1, s2; |
||
foreach (i; 0 .. height * width) { |
foreach (i; 0 .. height * width) { |
||
Line 571: | Line 575: | ||
void main() { |
void main() { |
||
enum int height = 8, width = 11; |
enum int height = 8, width = 11; |
||
showMaze(makeMaze( |
showMaze(makeMaze(width, height), width, height); |
||
}</lang> |
}</lang> |
||
Output example: |
Output example: |