Random Walk Generator on 2D Plane

  • Share this:

Code introduction


This function generates a random walk path on a two-dimensional plane, where each step randomly moves up, down, left, or right.


Technology Stack : random, math

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_walk(num_steps):
    import random
    import math

    x, y = 0, 0
    for _ in range(num_steps):
        direction = random.choice(['N', 'E', 'S', 'W'])
        if direction == 'N':
            y += 1
        elif direction == 'E':
            x += 1
        elif direction == 'S':
            y -= 1
        elif direction == 'W':
            x -= 1
    return x, y                
              
Tags: