[R] A Maze Generator

From: McGehee, Robert <Robert.McGehee_at_geodecapital.com>
Date: Tue, 29 Apr 2008 16:37:20 -0400

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 plots

    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

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

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue 29 Apr 2008 - 21:17:12 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 30 Apr 2008 - 00:30:32 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive