Maze generation: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 20:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F make_maze(w = 16, h = 8)
V vis = [[0] * w [+] [1]] * h [+] [[1] * (w + 1)]
V ver = [[‘| ’] * w [+] [String(‘|’)]] * h [+] [[String]()]
Line 49:
R s
 
print(make_maze())</langsyntaxhighlight>
 
{{out}}
Line 74:
=={{header|Action!}}==
Action! language does not support recursion. Therefore an iterative approach with a stack has been proposed.
<langsyntaxhighlight Actionlang="action!">DEFINE TOP="0"
DEFINE RIGHT="1"
DEFINE BOTTOM="2"
Line 188:
DO UNTIL CH#$FF OD
CH=$FF
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Maze_generation.png Screenshot from Atari 8-bit computer]
Line 196:
{{works with|GNAT}}
mazes.ads:
<langsyntaxhighlight Adalang="ada">generic
Height : Positive;
Width : Positive;
Line 222:
type Maze_Grid is array (Height_Type, Width_Type) of Cells;
 
end Mazes;</langsyntaxhighlight>
mazes.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
Line 397:
end Put;
end Mazes;
</syntaxhighlight>
</lang>
Example main.adb:
<langsyntaxhighlight Adalang="ada">with Mazes;
procedure Main is
package Small_Mazes is new Mazes (Height => 8, Width => 11);
Line 406:
Small_Mazes.Initialize (My_Maze);
Small_Mazes.Put (My_Maze);
end Main;</langsyntaxhighlight>
{{out}}
<pre>Starting generation at 3 x 7
Line 428:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">grid_maze(data b, integer N)
{
data d;
Line 501:
 
0;
}</langsyntaxhighlight>
{{out}}
<pre>+---+---+---+---+---+---+---+---+---+---+
Line 527:
 
=={{header|APL}}==
<syntaxhighlight lang="apl">
<lang APL>
This example shows how to use GNU APL scripting.
 
Line 633:
doMaze 9 9
)OFF
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 660:
=={{header|AutoHotkey}}==
For a challenge, this maze generation is entirely string based. That is to say, all operations including the wall removal and retrieval of cell states are done on the output string.
<langsyntaxhighlight AHKlang="ahk">; Initially build the board
Width := 11
Height := 8
Line 724:
If (A_Index = Y)
return SubStr(A_LoopField, x, 1)
}</langsyntaxhighlight>
{{out|Sample output}}
<pre>+-+-+-+-+-+-+-+-+-+-+-+
Line 750:
=={{header|AWK}}==
 
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
 
# Remember: AWK is 1-based, for better or worse.
Line 937:
srand(t);
}
</syntaxhighlight>
</lang>
 
Example output:
Line 987:
==={{header|QB64}}===
This implementation was written using QB64. It should also be compatible with Qbasic, as it uses no QB64-exclusive features.
<langsyntaxhighlight lang="qb64">OPTION BASE 0
RANDOMIZE TIMER
 
Line 1,054:
 
REM wait
DO: LOOP WHILE INKEY$ = ""</langsyntaxhighlight>
 
{{out}}
Line 1,081:
 
==={{header|BASIC256}}===
<langsyntaxhighlight lang="basic256">global size_x, size_y
size_x = 25
size_y = 15
Line 1,144:
print
next i
end subroutine</langsyntaxhighlight>
 
{{out}}
Line 1,182:
{{works with|Windows NT}}
 
<langsyntaxhighlight lang="dos">:amaze Rows Cols [wall char]
:: A stack-less, iterative, depth-first maze generator in native WinNT batch.
:: Rows and Cols must each be >1 and Rows*Cols cannot exceed 2096.
Line 1,276:
ENDLOCAL
EXIT /B 0
</syntaxhighlight>
</lang>
 
Example output:
Line 1,307:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> MazeWidth% = 11
MazeHeight% = 9
MazeCell% = 50
Line 1,348:
ENDIF
NEXT
ENDPROC</langsyntaxhighlight>
'''Sample output:'''
<br>
Line 1,358:
Also note that this requires an interpreter with working read-write memory support, which is suprisingly rare in online implementations. Padding the code page with extra blank lines or spaces can sometimes help. Using smaller dimensions might also be preferable, especially on slower implementations.
<langsyntaxhighlight lang="befunge">45*28*10p00p020p030p006p0>20g30g00g*+::"P"%\"P"/6+gv>$\1v@v1::\+g02+*g00+g03-\<
0_ 1!%4+1\-\0!::\-\2%2:p<pv0<< v0p+6/"P"\%"P":\+4%4<^<v-<$>+2%\1-*20g+\1+4%::v^
#| +2%\1-*30g+\1\40g1-:v0+v2?1#<v>+:00g%!55+*>:#0>#,_^>:!|>\#%"P"v#:*+*g00g0<>1
Line 1,364:
0#$g#<1#<-#<`#<\#<0#<^#_^/>#1+#4<>"P"%\"P"/6+g:2%^!>,1-:#v_$55+^|$$ "JH" $$>#<0
::"P"%\"P"/6+g40p\40g+\:#^"P"%#\<^ ::$_,#!0#:<*"|"<^," _"<:g000 <> /6+g4/2%+#^_
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,387:
=={{header|C}}==
Generation/solver in one. Requires UTF8 locale and unicode capable console. If your console font line-drawing chars are single width, define DOUBLE_SPACE to 0.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 1,532:
 
return 0;
}</langsyntaxhighlight>
{{out|Sample output}}
<pre>┌───┬─────┬─────────┬───────┬───┐
Line 1,554:
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Diagnostics;
Line 1,678:
}
}
</syntaxhighlight>
</lang>
Sample output:
<pre>
Line 1,726:
=={{header|C++}}==
[[File:maze_cpp.png|300px]]
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <iostream>
Line 1,996:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns maze.core
(:require [clojure.set :refer [intersection
select]]
Line 2,092:
 
;;Task
(println (maze->str (create-random-maze 10 10)))</langsyntaxhighlight>
 
{{out}}
Line 2,120:
Written in Commodore BASIC V2 and tested on Commodore 64 and Commodore 128 hardware. (It will also run on the unexpanded Commodore VIC-20 if you reduce the maze size to 8x8.) Due to stack size limitations in the operating systems, this solution eschews recursive subroutine calls. Recursion is accomplished by conditional branching within the maze build routine and the use of an array-based stack for data elements.
 
<langsyntaxhighlight BASIClang="basic">100 MS=10:REM MAZE SIZE
110 DIM S(MS+1,MS+1):REM SOUTH WALLS
120 DIM W(MS+1,MS+1):REM WEST WALLS
Line 2,178:
670 NEXT R
680 REM PRINT#4:CLOSE 4:REM CLOSE PRINTER DEVICE
690 RETURN</langsyntaxhighlight>
{{out|Output example (for 10x10 maze)}}
<pre>+--+--+--+--+--+--+--+--+--+--+
Line 2,205:
 
The remove-wall function has been written so as to be as close as possible to the specification. The walls are made from a single unicode character, specified by the block keyword, e. g. (maze 20 6 :block #\X). The BOX_DRAWINGS_LIGHT_DIAGONAL_CROSS character is used by default.
<langsyntaxhighlight lang="lisp">(defun shuffle (list) ;; Z not uniform
(sort list '> :key (lambda(x) (random 1.0))))
 
Line 2,234:
do (princ (aref maze i j))))))
 
(draw-maze 20 6)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,252:
 
Another solution using unicode line drawing chars. Assumes they are single width on console. Code pretty horribly unreadable.
<langsyntaxhighlight lang="lisp">(setf *random-state* (make-random-state t))
 
(defun 2d-array (w h)
Line 2,308:
(show))))
 
(make-maze 20 20)</langsyntaxhighlight>
{{out}}
<pre>┼───┴───┼───┴───┴───┼───┴───┴───┼
Line 2,329:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() @safe {
import std.stdio, std.algorithm, std.range, std.random;
 
Line 2,350:
foreach (const a, const b; hor.zip(ver ~ []))
join(a ~ "+\n" ~ b).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
Line 2,374:
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+</pre>
=={{header|Delphi}}==
<langsyntaxhighlight Pascallang="pascal">program MazeGen_Rosetta;
 
{$APPTYPE CONSOLE}
Line 2,485:
Main;
 
end.</langsyntaxhighlight>
{{out}}
<pre>+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
Line 2,516:
[https://easylang.online/apps/_r_maze0.html Run it]
 
<syntaxhighlight lang="text">size = 20
n = 2 * size + 1
endpos = n * n - 2
Line 2,568:
.
call make_maze
call show_maze</langsyntaxhighlight>
 
=={{header|EGL}}==
<langsyntaxhighlight EGLlang="egl">program MazeGen
 
// First and last columns/rows are "dead" cells. Makes generating
Line 2,720:
end
 
end</langsyntaxhighlight>
{{out|Output example (for 10x10 maze)}}
<pre>
Line 2,748:
=={{header|Elixir}}==
{{trans|D}}
<langsyntaxhighlight lang="elixir">defmodule Maze do
def generate(w, h) do
maze = (for i <- 1..w, j <- 1..h, into: Map.new, do: {{:vis, i, j}, true})
Line 2,778:
end
 
Maze.generate(20, 10)</langsyntaxhighlight>
 
{{out}}
Line 2,806:
 
=={{header|Elm}}==
<langsyntaxhighlight lang="elm">import Maybe as M
import Result as R
import Matrix
Line 3,054:
, update = update
, subscriptions = subscriptions
}</langsyntaxhighlight>
 
Link to live demo: http://dc25.github.io/mazeGenerationElm/
Line 3,061:
{{libheader|cl-lib}}
 
<langsyntaxhighlight lang="lisp">(require 'cl-lib)
 
(cl-defstruct maze rows cols data)
Line 3,253:
(print-maze maze solution)))
 
(generate 20 20)</langsyntaxhighlight>
 
{{out}}
Line 3,284:
 
===Using multiple processes===
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( maze ).
 
Line 3,428:
[Pid ! {Key, My_pid} || {_Position, Pid} <- Position_pids],
[{Position, read_receive(Pid, Key)} || {Position, Pid} <- Position_pids].
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,464:
 
Usage: start with generate_default/0. Use generate_MxN() to test other maze sizes.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module(maze).
-record(maze, {g, m, n}).
Line 3,579:
generate_default() ->
generate_MxN(9, 9).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,607:
=={{header|F_Sharp|F#}}==
Using mutable state in the form of 2D arrays:
<langsyntaxhighlight lang="fsharp">let rnd : int -> int =
let gen = new System.Random()
fun max -> gen.Next(max)
Line 3,663:
 
let m = new Maze(10,10)
m.Print()</langsyntaxhighlight>
{{out|Output example}}
<pre>+-+-+-+-+-+-+-+-+-+-+
Line 3,692:
The solution uses the following library <tt>bits.fs</tt>, which implements bit-arrays:
<br>
<langsyntaxhighlight lang="forth">\ Bit Arrays
 
: to-bits ( c -- f f f f f f f f )
Line 3,802:
else
drop
then ;</langsyntaxhighlight>
<br>
The solution uses three bit-arrays: one to track whether a cell has been visited, one for "East"-walls (walls to the right of a cell) and one for "South"-walls (walls to the bottom of a cell).
<br>
<langsyntaxhighlight lang="forth">#! /usr/bin/gforth
\ Maze Generation
 
Line 3,927:
: maze ( width height -- ) build-maze maze. ;
 
maze cr bye</langsyntaxhighlight>
 
{{out}}<pre>
Line 4,007:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 04-12-2016
' compile with: fbc -s console
' when generating a big maze it's possible to run out of stack space
Line 4,136:
Loop
 
End</langsyntaxhighlight>
 
=={{header|Fōrmulæ}}==
Line 4,147:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 4,265:
m.gen()
fmt.Print(m)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,280:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
 
Line 4,357:
 
main :: IO ()
main = getStdGen >>= stToIO . maze 11 8 >>= printMaze</langsyntaxhighlight>
{{out|Sample output}}
+---+---+---+---+---+---+---+---+---+---+---+
Line 4,378:
 
=={{header|Huginn}}==
<langsyntaxhighlight lang="huginn">import Algorithms as algo;
import Mathematics as math;
import Terminal as term;
Line 4,448:
maze = Maze( rows, cols );
print( "{}".format( maze ) );
}</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
[[File:Mazegen-unicon-20x30-1321112170.gif|thumb|right|20x30 with two random openings]]
[[File:Mazegen-unicon-20x30-1321060467.gif|thumb|right|20x30 with opposite openings]]
<langsyntaxhighlight Iconlang="icon">link printf
 
procedure main(A) # generate rows x col maze
Line 4,545:
 
return mazeinfo(&window,maze,sprintf("maze-%dx%d-%d.gif",r,c,&now))
end</langsyntaxhighlight>
Note: The underlying maze structure (matrix) is uni-directional from the start
{{libheader|Icon Programming Library}}
Line 4,555:
{{trans|PicoLisp}}
But without any relevant grid library:
<langsyntaxhighlight lang="j">maze=:4 :0
assert.0<:n=.<:x*y
horiz=. 0$~x,y-1
Line 4,585:
'hdoor vdoor'=. 2 4&*&.>&.> (#&,{@;&i./@$)&.> y
' ' (a:-.~0 1;0 2; 0 3;(2 1-~$text);(1 4&+&.> hdoor),,vdoor+&.>"0/2 1;2 2;2 3)} text
)</langsyntaxhighlight>
The result of <code>maze</code> is a pair of arrays: one for open "doors" in the horizontal direction and the other for open "doors" in the vertical direction. The entry and exit doors are not represented by <code>maze</code> -- they are implicitly defined and are implemented in <code>display</code>. (The sequences of coordinates in <code>display</code> are the relative coordinates for the doors. For example, <code>2 1;2 2;2 3</code> are where we put spaces for each vertical door. The variable <code>text</code> is an ascii representation of the maze grid before the doors are placed.)
 
{{out|Example use (with ascii box drawing enabled)}}
<langsyntaxhighlight lang="j"> display 8 maze 11
+ +---+---+---+---+---+---+---+---+---+---+
| | | | |
Line 4,606:
+ + + + + + + + +---+ + +
| | | | |
+---+---+---+---+---+---+---+---+---+---+---+</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">package org.rosettacode;
 
import java.util.Collections;
Line 4,700:
}
 
}</langsyntaxhighlight>
{{out}}
<pre>+---+---+---+---+---+---+---+---+---+---+
Line 4,726:
=={{header|JavaScript}}==
{{trans|J}}
<langsyntaxhighlight lang="javascript">function maze(x,y) {
var n=x*y-1;
if (n<0) {alert("illegal maze dimensions");return;}
Line 4,788:
}
return text.join('');
}</langsyntaxhighlight>
Variable meanings in function <code>maze</code>:
# <code>x</code>,<code>y</code> — dimensions of maze
Line 4,806:
 
{{out|Example use}}
<langsyntaxhighlight lang="html"><html><head><title></title></head><body><pre id="out"></pre></body></html>
<script type="text/javascript">
/* ABOVE CODE GOES HERE */
document.getElementById('out').innerHTML= display(maze(8,11));
</script></langsyntaxhighlight>
produced output:
<pre>+ +---+---+---+---+---+---+---+---+---+---+
Line 4,832:
 
For example, change replace the line <code>while (0<n) {</code> with:
<langsyntaxhighlight lang="javascript"> function step() {
if (0<n) {</langsyntaxhighlight>
And replace the closing brace for this while loop with:
<langsyntaxhighlight lang="javascript"> document.getElementById('out').innerHTML= display({x: x, y: y, horiz: horiz, verti: verti, here: here});
setTimeout(step, 100);
}
}
step();</langsyntaxhighlight>
To better see the progress, you might want a marker in place, showing the position being considered. To do that, replace the line which reads <code>if (0 == k%4) {</code> with
<langsyntaxhighlight lang="javascript"> if (m.here && m.here[0]*2+1 == j && m.here[1]*4+2 == k)
line[k]= '#'
else if (0 == k%4) {</langsyntaxhighlight>
Note however that this leaves the final '#' in place on maze completion, and that the function <code>maze</code> no longer returns a result which represents a generated maze.
 
Note also that this display suggests an optimization. You can replace the line reading <code>path.push(here= next);</code> with:
<langsyntaxhighlight lang="javascript"> here= next;
if (1 < neighbors.length)
path.push(here);</langsyntaxhighlight>
And this does indeed save a negligible bit of processing, but the maze algorithm will still be forced to backtrack through a number of locations which have no unvisited neighbors.
===HTML Table===
Using HTML, CSS and table cells for maze.
<langsyntaxhighlight lang="html"><html><head><title>Maze maker</title>
<style type="text/css">
table { border-collapse: collapse }
Line 4,967:
<a href="javascript:make_maze()">Generate</a>
<a id='solve' style='display:none' href='javascript:solve(); void(0)'>Solve</a>
</fieldset></form><table id='maze'/></body></html></langsyntaxhighlight>
 
=={{header|Julia}}==
Line 4,973:
 
'''Generating functions'''
<langsyntaxhighlight lang="julia">using Random
check(bound::Vector) = cell -> all([1, 1] .≤ cell .≤ bound)
neighbors(cell::Vector, bound::Vector, step::Int=2) =
Line 4,992:
firstcell = 2 * [rand(1:w), rand(1:h)]
return walk(maze, firstcell)
end</langsyntaxhighlight>
 
'''Printing functions'''
<langsyntaxhighlight lang="julia">pprint(matrix) = for i = 1:size(matrix, 1) println(join(matrix[i, :])) end
function printmaze(maze)
walls = split("╹ ╸ ┛ ╺ ┗ ━ ┻ ╻ ┃ ┓ ┫ ┏ ┣ ┳ ╋")
Line 5,008:
 
printmaze(maze(10, 10))
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,025:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">import java.util.*
 
class MazeGenerator(val x: Int, val y: Int) {
Line 5,091:
display()
}
}</langsyntaxhighlight>
 
=={{header|Lua}}==
{{Works with|Lua|5.1}}
<syntaxhighlight lang="lua">
<lang Lua>
math.randomseed( os.time() )
 
Line 5,169:
 
print(make_maze())
</syntaxhighlight>
</lang>
{{Out}}
<pre>#################################
Line 5,204:
INT((currentx% + oldx%) / 2) return a double, because has 2 as double so we get (integer+integer)/double or integer/double or double. Int(0.5) return.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Maze {
width% = 40
Line 5,261:
}
Maze
</syntaxhighlight>
</lang>
 
===Depth-first search===
Line 5,271:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Maze2 {
\\ depth-first search
Line 5,342:
}
Maze2
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">MazeGraphics[m_, n_] :=
Block[{$RecursionLimit = Infinity,
unvisited = Tuples[Range /@ {m, n}], maze},
Line 5,359:
RandomSample@{# + {0, 1}, # - {0, 1}, # + {1, 0}, # - {1,
0}}}]} &@RandomChoice@unvisited; maze];
maze = MazeGraphics[21, 13]</langsyntaxhighlight>
{{Out}}
[[File:MathematicaMazeGraphics.png]]
Line 5,365:
{{Works with|Mathematica|9.0}}
Here I generate a maze as a graph. Vertices of the graph are cells and edges of the graph are removed walls. This version is mush faster and is convenient to solve.
<langsyntaxhighlight lang="mathematica">MazeGraph[m_, n_] :=
Block[{$RecursionLimit = Infinity, grid = GridGraph[{m, n}],
unvisitedQ}, unvisitedQ[_] := True;
Line 5,375:
RandomChoice@VertexList@grid][[2, 1]],
GraphLayout -> {"GridEmbedding", "Dimension" -> {m, n}}]];
maze = MazeGraph[13, 21]</langsyntaxhighlight>
{{Out}}
[[File:MathematicaMazeGraph.png]]
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight Matlablang="matlab">function M = makeMaze(n)
showProgress = false;
 
Line 5,432:
 
image(M-VISITED);
axis equal off;</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|D}}
<langsyntaxhighlight lang="nim">import random, sequtils, strutils
randomize()
 
Line 5,466:
walk rand(0..<w), rand(0..<h)
for a,b in zip(hor, ver & @[""]).items:
echo join(a & "+\n" & b)</langsyntaxhighlight>
 
{{out}}
Line 5,497:
This difers of the basic Javascript in that in NodeJS we take advantage of the asynchronous behaviour. This code was modified from the plain Javascript section to make it '''Asynchronous''' and able to run under ''strict mode''.
 
<langsyntaxhighlight lang="javascript">
'use strict';
/*
Line 5,597:
display: display
}
</syntaxhighlight>
</lang>
 
{{out|Example use}}
Line 5,603:
Here is a basic example of what your main file should contain:
 
<langsyntaxhighlight lang="javascript">
'use strict';
 
Line 5,620:
}, (err) => console.error(err));
 
</syntaxhighlight>
</lang>
 
Sample Output:
Line 5,651:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let seen = Hashtbl.create 7
let mark t = Hashtbl.add seen t true
let marked t = Hashtbl.mem seen t
Line 5,697:
Random.self_init();
visit (Random.int nx, Random.int ny);
print_maze ();</langsyntaxhighlight>
Output from 'ocaml gen_maze.ml 10 10':<pre>+---+---+---+---+---+---+---+---+---+---+
| | | |
Line 5,722:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
; maze generation
(import (otus random!))
Line 5,760:
(loop nx ny)))
(try))))))
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="scheme">
; maze printing:
(display "+")
Line 5,784:
maze)
(print)
</syntaxhighlight>
</lang>
{{out|Sample 30 x 8 output}}
<pre>+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Line 5,805:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use List::Util 'max';
 
my ($w, $h) = @ARGV;
Line 5,840:
print @{$hor[$_]}, "+\n";
print @{$ver[$_]}, "|\n" if $_ < $h;
}</langsyntaxhighlight>
Run as <code>maze.pl [width] [height]</code> or use default dimensions.
{{out|Sample 4 x 1 output}}
Line 5,850:
Adapted a couple of techniques from the excellent D submission<br>
(however this holds the grid as an array of complete lines)
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #000080;font-style:italic;">--
Line 5,898:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">grid</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'\n'</span><span style="color: #0000FF;">))</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 5,922:
=={{header|PHP}}==
Code inspired by the D and Python solutions (with the implementation of backtracking, or sometimes it wouldn't work). Could have been done procedurally or fully OO (with cells as class too). A debug flag has been provided to allow following the inner workings. Works on PHP > 5.6.
<langsyntaxhighlight lang="php"><?php
class Maze
{
Line 6,069:
 
$maze = new Maze(10,10);
$maze->printOut();</langsyntaxhighlight>
{{out}}
<pre>
Line 6,096:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">main =>
gen_maze(8,8).
 
Line 6,156:
end,
println("+").
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,180:
=={{header|PicoLisp}}==
This solution uses 'grid' from "lib/simul.l" to generate the two-dimensional structure.
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l")
 
(de maze (DX DY)
Line 6,209:
 
(de display (Maze)
(disp Maze 0 '((This) " ")) )</langsyntaxhighlight>
{{out}}
<pre>: (display (maze 11 8))
Line 6,233:
=={{header|PL/I}}==
{{trans|REXX}}
<langsyntaxhighlight lang="pli">*process source attributes xref or(!);
mgg: Proc Options(main);
/* REXX ***************************************************************
Line 6,449:
 
End;
End;</langsyntaxhighlight>
Output:
<pre>
Line 6,468:
 
=={{header|Processing}}==
<langsyntaxhighlight lang="java">int g_size = 10;
color background_color = color (80, 80, 220);
color runner = color (255, 50, 50);
Line 6,594:
if(wall[3]) line((j+1)*c_size, i*c_size, j*c_size, i*c_size);
}
}</langsyntaxhighlight>
'''It can be played on line''' :<BR> [https://www.openprocessing.org/sketch/880778/ here.]
 
==={{header|Processing Python mode}}===
 
<langsyntaxhighlight lang="python">
g_size = 10
background_color = color(80, 80, 220)
Line 6,722:
if wall[2]: line((j + 1) * c_size, (i + 1) * c_size, (j + 1) * c_size, i * c_size)
if wall[3]: line((j + 1) * c_size, i * c_size, j * c_size, i * c_size)
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
Works with SWI-Prolog and XPCE.
<langsyntaxhighlight Prologlang="prolog">:- dynamic cell/2.
 
maze(Lig,Col) :-
Line 6,816:
\+cell(L, C1).
 
</syntaxhighlight>
</lang>
{{out}}
[[File:Prolog-Maze.jpg]]
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Enumeration
;indexes for types of offsets from maze coordinates (x,y)
#visited ;used to index visited(x,y) in a given direction from current maze cell
Line 6,956:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
The maze is represented by an array of cells where each cell indicates the walls present above (#dir_N) and to its left (#dir_W). Maze generation is done with a additional array marking the visited cells. Neither an entry nor an exit are created, these were not part of the task. A simple means of doing so is included but has been commented out.
 
Line 6,980:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from random import shuffle, randrange
 
def make_maze(w = 16, h = 8):
Line 7,006:
 
if __name__ == '__main__':
print(make_maze())</langsyntaxhighlight>
{{out}}
<pre>+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Line 7,029:
 
Maze generator
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 7,060:
; return the result
(maze N M tbl))
</syntaxhighlight>
</lang>
 
Printing out the maze
 
<langsyntaxhighlight lang="racket">
;; Shows a maze
(define (show-maze m)
Line 7,084:
(displayln "+"))
(newline))
</syntaxhighlight>
</lang>
 
Example:
Line 7,111:
{{works with|rakudo|2015-09-22}}
Supply a width and height and optionally the x,y grid coords for the starting cell. If no starting cell is supplied, a random one will be selected automatically. 0,0 is the top left corner.
<syntaxhighlight lang="raku" perl6line>constant mapping = :OPEN(' '),
:N< ╵ >,
:E< ╶ >,
Line 7,197:
}
display gen_maze( 29, 19 );</langsyntaxhighlight>
{{out}}
<small><pre style="font-family: consolas, inconsolata, monospace; line-height: normal;">┌ ╵ ────────────────────────────┬───────────────────────────────────────────┬───────────┬───────────────────────────┐
Line 7,241:
=={{header|Rascal}}==
{{trans|Python}}
<langsyntaxhighlight lang="rascal">import IO;
import util::Math;
import List;
Line 7,269:
println(("" | it + "<z>" | z <- b));
}
}</langsyntaxhighlight>
 
<pre>rascal>make_maze(10,10)
Line 7,298:
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red ["Maze generation"]
 
size: as-pair to-integer ask "Maze width: " to-integer ask "Maze height: "
Line 7,345:
]
print ""
]</langsyntaxhighlight>
{{out}}
<pre>Maze width: 15
Line 7,371:
In order to preserve the aspect ratio (for most display terminals), several &nbsp; '''changestr''' &nbsp; invocations and
<br>some other instructions were added to increase the horizontal dimension (cell size).
<langsyntaxhighlight lang="rexx">/*REXX program generates and displays a rectangular solvable maze (of any size). */
parse arg rows cols seed . /*allow user to specify the maze size. */
if rows='' | rows==',' then rows= 19 /*No rows given? Then use the default.*/
Line 7,467:
otherwise nop
end /*select*/
end /*k*/; return</langsyntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
 
Line 7,527:
The above REXX version had a quite of bit of code to "dress up" the maze presentation, &nbsp; so a slimmed-down version
<br>was included here for easier reading and understanding of the program's logic.
<langsyntaxhighlight lang="rexx">/*REXX program generates and displays a rectangular solvable maze (of any size). */
parse arg rows cols seed . /*allow user to specify the maze size. */
if rows='' | rows=="," then rows= 19 /*No rows given? Then use the default.*/
Line 7,580:
if hood(rr,cc)==1 then do; r!= rr; c!= cc; @.r!.c!= 0; return 1; end
end /*c*/ /* [↑] r! and c! are used by invoker.*/
end /*r*/; return 0</langsyntaxhighlight>
{{out|output|text=&nbsp; when using input: &nbsp; &nbsp; <tt> 10 &nbsp;10 </tt>}}
 
Line 7,610:
 
===version 3===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 04.09.2013 Walter Pachl
**********************************************************************/
Line 7,777:
End
End
Return is js /* return the new start point*/</langsyntaxhighlight>
Output:
<pre>
Line 7,798:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Maze
DIRECTIONS = [ [1, 0], [-1, 0], [0, 1], [0, -1] ]
Line 7,892:
# Demonstration:
maze = Maze.new 20, 10
maze.print</langsyntaxhighlight>
 
{{out}}
Line 7,921:
=={{header|Rust}}==
Uses the [https://crates.io/crates/rand rand] library
<langsyntaxhighlight lang="rust">use rand::{thread_rng, Rng, rngs::ThreadRng};
 
const WIDTH: usize = 16;
Line 8,057:
maze.open_doors();
maze.paint();
}</langsyntaxhighlight>
 
{{out}}
Line 8,095:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import scala.util.Random
 
object MazeTypes {
Line 8,180:
private def openInDirection(loc: Loc, dir: Direction): Boolean =
doors.contains(Door(loc, loc + dir)) || doors.contains(Door(loc + dir, loc))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 8,218:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var(w:5, h:5) = ARGV.map{.to_i}...
var avail = (w * h)
 
Line 8,250:
say (ver[i].join('') + '|')
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 8,267:
 
=={{header|SuperCollider}}==
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
// some useful functions
(
Line 8,324:
w.front.refresh;
)
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
{{works with|Swift|3}}
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
extension Array {
Line 8,496:
let y = 10
let maze = MazeGenerator(x, y)
maze.display()</langsyntaxhighlight>
{{out}}
<pre>
Line 8,523:
=={{header|Tcl}}==
{{trans|Javascript}}
<langsyntaxhighlight lang="tcl">package require TclOO; # Or Tcl 8.6
 
# Helper to pick a random number
Line 8,619:
# Demonstration
maze create m 11 8
puts [m view]</langsyntaxhighlight>
{{out}}
<pre>
Line 8,647:
Legend: cu = current location; vi = boolean hash of visited locations; pa = hash giving a list neighboring cells to which there is a path from a given cell.
 
<langsyntaxhighlight lang="txr">@(bind (width height) (15 15))
@(do
(defvar *r* (make-random-state nil))
Line 8,701:
@;;
@(bind m @(make-maze width height))
@(do (print-maze m width height))</langsyntaxhighlight>
 
{{out}}
Line 8,766:
At the user interface level, the straightness parameter is represented as a percentage. This percentage is converted to a number of cells based on the width and height of the maze. For instance if the straightness parameter is 15, and the maze size is 20x20, it means that 15% out of 400 cells, or 60 cells will be traversed before the queue is scrambled. Then another 60 will be traversed and the queue will be scrambled, and so forth.
 
<langsyntaxhighlight lang="txrlisp">(defvar vi) ;; visited hash
(defvar pa) ;; path connectivity hash
(defvar sc) ;; count, derived from straightness fator
Line 8,845:
(set h (max 1 h))
(print-maze (make-maze w h s) w h))
(else (usage))))</langsyntaxhighlight>
 
{{out}}
Line 8,960:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code Ran=1, CrLf=9, Text=12; \intrinsic routines
def Cols=20, Rows=6; \dimensions of maze (cells)
int Cell(Cols+1, Rows+1, 3); \cells (plus right and bottom borders)
Line 9,003:
Text(0, if Y#Rows & Cell(X, Y, LeftWall) then "| " else " ");
];
]</langsyntaxhighlight>
 
Output:
Line 9,025:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="ecmascript">import "random" for Random
import "os" for Process
 
Line 9,111:
var mg = MazeGenerator.new(x, y)
mg.generate(0, 0)
mg.display()</langsyntaxhighlight>
 
{{out}}
Line 9,138:
Generate a maze without marked entry or exit points.
{{trans|Python}}
<langsyntaxhighlight lang="zkl">
fcn make_maze(w = 16, h = 8){
// make arrays with lists of lists (all mutable)
Line 9,159:
return(ver,hor);
}
make_maze();</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits