[R] A Maze Generator

Peter Dalgaard p.dalgaard at biostat.ku.dk
Tue Apr 29 23:33:53 CEST 2008


McGehee, Robert wrote:
> 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! 
> --Robert
>
> PS. Feel free to pass along suggestions or comments.
>
>   
You have prb[i] <-p but no definition of i. What was intended?

    -pd
> ----------------------------------------------------------------
> 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",
> lwd=lwd)
>     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
>             break
>         }
>     }
>     z
> }
> set.seed(1)
> 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}}
>
> ______________________________________________
> 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.
>   


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907



More information about the R-help mailing list