[R] A Maze Generator

McGehee, Robert Robert.McGehee at geodecapital.com
Tue Apr 29 22:37:20 CEST 2008

I had some fun this afternoon coding up a 'maze generator' in R. I
thought I'd pass along the fruits of my labor for everyone's amusement.

As written, every point is connected to every other point, so feel free
to 'start' and 'finish' anywhere you like.

Have fun! 

PS. Feel free to pass along suggestions or comments.

plotMaze <- function(z, text=FALSE, lwd=2, ...) {
    N <- nrow(z)
    y <- -matrix(rep(1:N, N), N, N, byrow=FALSE)-1
    x <- matrix(rep(1:N, N), N, N, byrow=TRUE)
    plot(1:(N+1), -1:-(N+1), type="n", ylab="", xlab="", axes=FALSE,
    segments(1, -1:-(N+1) , N+1, -1:-(N+1), lwd=lwd)
    segments(1:(N+1), -1, 1:(N+1), -(N+1), lwd=lwd)
    segments(x+(z==4), y+(z==3), x+(z!=2), y+(z!=1), col="white",
    if (text) text(x+0.5, y+0.5, z)
    rect(1, -1, N+1, -(N+1), lwd=lwd)

makeMaze <- function(N, p=1) { # large 'p' may result in more order
    z <- matrix(NA+0, N, N)
    s <- function(x) if (length(x)==1) x else sample(x, size=1)
    z[s(1:length(z))] <- 0
    while (any(is.na(z))) {
        xx <- list(z[c(2:N, N),],
                   z[,c(1, 1:(N-1))],
                   z[c(1, 1:(N-1)),],
                   z[,c(2:N, N)])
        xx[[1]][N,] <- NA; xx[[2]][,1] <- NA; xx[[3]][1,] <- NA;
xx[[4]][,N] <- NA
        prb <- rep(1, 4); prb[i] <- p
        for (i in sample(1:4, prob=prb)) {
            q <- !is.na(xx[[i]]) & is.na(z)
            if (!any(q)) next
            z[s(which(q))] <- i
plotMaze(makeMaze(10), main="Simple Maze")
plotMaze(makeMaze(25), main="Hard  Maze", lwd=1)

Robert McGehee, CFA
Geode Capital Management, LLC
One Post Office Square, 28th Floor | Boston, MA | 02109
Tel: 617/392-8396    Fax:617/476-6389
mailto:robert.mcgehee at geodecapital.com

This e-mail, and any attachments hereto, are intended fo...{{dropped:11}}

More information about the R-help mailing list