Random Walk Maximum Distance Calculator

  • Share this:

Code introduction


This function simulates a simple random walk process and calculates the maximum distance between any two points in the walk. The function initializes a starting point, then randomly selects a direction to move, records the position of each step, and calculates the maximum distance.


Technology Stack : Packages and technologies used in the code[English]

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_walk(num_steps):
    import random
    import math
    import time
    import string
    import os
    import sys
    import hashlib
    import json
    import re
    import shutil

    # 初始化起点
    x, y = 0, 0
    walk = [(x, y)]

    # 生成随机步骤
    for _ in range(num_steps):
        direction = random.choice(['up', 'down', 'left', 'right'])
        if direction == 'up':
            y += 1
        elif direction == 'down':
            y -= 1
        elif direction == 'left':
            x -= 1
        elif direction == 'right':
            x += 1
        walk.append((x, y))

    # 计算最大距离
    max_distance = 0
    for i in range(len(walk) - 1):
        dx = walk[i][0] - walk[i + 1][0]
        dy = walk[i][1] - walk[i + 1][1]
        distance = math.sqrt(dx**2 + dy**2)
        max_distance = max(max_distance, distance)

    # 返回结果
    return max_distance