random_walk_2d_avoid_simulation, an Octave code which simulates a self-avoiding random walk in a 2D region.

A random self-avoiding walk of length STEP_NUM in 2D can be generated by generating a random walk in 2D and "hoping" it doesn't intersect itself. If the next step would cause an intersection, then the generation is terminated prematurely; to ensure that the self-avoiding random walks are selected uniformly, we have to just keep trying random walks this way and "hoping".

random_walk_2d_avoid_plot() plots the trajectories of one or more self-avoiding random walks. The user gives a desired length STEP_NUM, and the code generates a random walk that either reaches STEP_NUM without self-intersection, or is terminated early to avoid intersection.

random_walk_2d_avoid_simulation() plots averaged data for any number of self-avoiding random walks that each try to achieve the same number of steps. The data plotted includes the number of steps each walk reached before termination, and a least squares fit to the distance versus number of steps.


random_walk_2d_avoid_plot ( step_num, walk_num )

random_walk_2d_avoid_simulation ( step_num, walk_num )


The computer code and data files described and made available on this web page are distributed under the MIT license


random_walk_2d_avoid_simulation is available in a MATLAB version and an Octave version.

Related Data and codes:


octave_simulation, an Octoave code which uses simulation to study card games, contests, and other processes which have a random element. Usually, the purpose is to try to predict the average behavior of the system over many trials.


  1. Brian Hayes,
    How To Avoid Yourself,
    American Scientist,
    Volume 86, Number 4, July-August 1998, pages 314-319.

Source Code:

Last revised on 10 March 2019.