Random Walk Algorithm for 2D Plane

  • Share this:

Code introduction


This function implements a simple random walk algorithm to generate a random walking path for a point in a two-dimensional plane.


Technology Stack : random, collections, math

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_walk(n):
    from random import choice
    from collections import deque
    from math import sqrt

    def distance(p1, p2):
        return sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)

    walk = deque([(0, 0)])
    for _ in range(n):
        x, y = walk[-1]
        move = choice([(-1, 0), (1, 0), (0, -1), (0, 1)])
        walk.append((x + move[0], y + move[1]))
    return walk