I want to simulate a self avoiding random walk in two dimension on a square lattice and plot the path.
So far I have written out the code for this problem:
n <- 100
x <- 0
y <- 0
randomwalkx <- 0
randomwalky <- 0
for(i in 1:n){
random <- sample(0:3, 1)
if(random == 0){x <- x+1}
if(random == 1){x <- x-1}
if(random == 2){y <- y+1}
if(random == 3){y <- y-1}
xcheck <- x %in% randomwalkx
ycheck <- y %in% randomwalky
if(ycheck == "TRUE" && xcheck == "TRUE"){
if(random==0){x<-x-1}
if(random==1){x<-x+1}
if(random==2){y<-y-1}
if(random==3){y<-y+1}
}else{
randomwalkx <- c(randomwalkx, x)
randomwalky <- c(randomwalky, y)
}
}
plot(randomwalkx,randomwalky,xlab='x',ylab='y')
lines(randomwalkx,randomwalky,type='b')
However the path only travels in one diagonal direction. Can anyone see a mistake I have made or solve this problem?
The problem is in this line:
if(ycheck=="TRUE"&&xcheck=="TRUE"){
What that line is doing is making it so that your walk can't "go backwards". Let's say your walk goes randomwalkx=(0,1,1,2), randomwalky=(0,0,-1,-1) and your next roll gives you x = x-1: the next coordinates would be 1,-1. Both x=1 and y=-1 exist in your random walk history, so your loop will re-roll until you keep going in the same direction for either x or y.
You can fix this by changing the line to something like
if(paste(x,y) %in% paste(randomwalkx, randomwalky)){