-1

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?

Dason
  • 60,663
  • 9
  • 131
  • 148
Job
  • 33
  • 1
  • 7
  • can you please tell us **why** you want to delete this question? – Ben Bolker Apr 21 '15 at 12:14
  • that's not a "why" ... – Ben Bolker Apr 21 '15 at 12:15
  • 1
    As much as I think that you shouldn't be asking online questions if you don't want them to stay online the best thing to do is to flag the question for the moderators to delete. However: "The standard policy for moderators is to decline such flags." See http://meta.stackexchange.com/questions/5221/how-does-deleting-work-what-can-cause-a-post-to-be-deleted-and-what-does-that – nico Apr 21 '15 at 12:23
  • @JoeBampton please read very well the explanation on that link, especially the part regarding "If you posted a question that you regret posting" that links to the [Terms of Service](http://stackexchange.com/legal) that you have agreed to when using this website. Those state that: *"You agree that all Subscriber Content that You contribute to the Network is perpetually and irrevocably licensed to Stack Exchange under the Creative Commons Attribution Share Alike license"* – nico Apr 21 '15 at 12:27

1 Answers1

2

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)){
C_Z_
  • 7,427
  • 5
  • 44
  • 81