Skip to content

Instantly share code, notes, and snippets.

@dreidpath
Last active May 23, 2016 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dreidpath/b2f92747dad0b38926a20162dbc07d94 to your computer and use it in GitHub Desktop.
Save dreidpath/b2f92747dad0b38926a20162dbc07d94 to your computer and use it in GitHub Desktop.
A Monte Carlo simulation of random walks in flatland, to see how long it takes an agent (p) to visit every unit in flatland at least once
# A random-walk in flat-land. Note that the world is a circle.
maxworld <- 1000 # Flatland is maxworld units long
p <- integer(maxworld/2) # place p on the unit halfway between 0 and maxworld
dist <- c() # dist: the distribution of "times it took to complete each iter(ation) of the randmo walk"
for(loop in 1:1000){ # Run the siumulation of random walks 1000 times
world <- rep(0, maxworld) # Set up the world, as maxworld-long unvisited units
keep_going <- T # keep_going determined whether a random walk simulation continues
iter <- 0 # iter is a count of the number of the number of time p moved around flatland before every unit in flatland was visited at least once
while(keep_going == T){ # Move p around flatland until every unit has been visited at least once
iter <- iter + 1 # Count the number of time p moved
p <- ifelse (runif(1, -1, 1)<0, p-1, p+1) # p's movement is a random walk
p <- ifelse(p > maxworld, 1, p) # Make sure p moves in a circle around the world
p <- ifelse(p < 1, maxworld, p) # Make sure p moives in a circle around the world
world[p] <- world[p] + 1 # count the number of time p visited each unit in the world
if(sum(world==0) == 0){ # If every unit in the world has been visited
keep_going <- F} # set keep-going to false, so the whiule loop fails.
}
dist <- c(dist, iter) # add the number of moves made in this random-walk and add it to the vector of random walks
}
# Plot the distribution of random-walks
plot(dist, xlab = "Iterations to Completion")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment