simulate a self-avoiding random walk in python

To simulate a self-avoiding random walk, we can use a simple algorithm that generates a random walk path while ensuring that the path does not cross itself. Here's a Python implementation of this algorithm:

main.py
import numpy as np

def self_avoiding_walk(n_steps):
    # starting position of the walk
    pos = np.array([0, 0])

    # the list of visited positions
    path = [pos]

    # possible moves - up, down, left, right
    moves = np.array([[0, 1], [0, -1], [1, 0], [-1, 0]])

    # generate n_steps random moves
    for i in range(n_steps):
        # generate a random move
        move = moves[np.random.choice(len(moves))]

        # calculate new position after the move
        new_pos = pos + move

        # check if the new position is already visited
        if not any((new_pos == p).all() for p in path):
            # add the new position to the path
            path.append(new_pos)

            # set the current position to the new position
            pos = new_pos

    return path
796 chars
30 lines

This function takes an integer n_steps as input, which represents the number of random moves to generate. It returns a list of positions visited by the walk.

To visualize the walk, we can use the matplotlib library as follows:

main.py
import matplotlib.pyplot as plt

# generate a self-avoiding walk with 1000 steps
path = self_avoiding_walk(1000)

# plot the path
fig, ax = plt.subplots()
ax.plot([p[0] for p in path], [p[1] for p in path])
ax.set_aspect('equal', adjustable='box')
plt.show()
259 chars
11 lines

This will generate a plot of the self-avoiding random walk path.

gistlibby LogSnag