import random

import matplotlib.pyplot as plt

import datetime


def random_walk(N):

    path = [(0, 0)]

    for _ in range(N):

        x, y = path[-1]

        direction = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)])

        next_step = (x + direction[0], y + direction[1])

        path.append(next_step)

    return path


def loop_erasure(path):

    latest_occurrence = {}

    for i, point in enumerate(path):

        latest_occurrence[point] = i

    erased_path = []

    i = 0

    while i < len(path):

        point = path[i]

        erased_path.append(point)

        i = latest_occurrence[point] + 1

    return erased_path


def plot_paths(path, erased_path):

    x_erased, y_erased = zip(*erased_path)

    plt.figure(figsize=(8, 8))

    plt.plot(x_erased, y_erased, color='black', linestyle='-', linewidth=2, label='Erased Path')

    plt.gca().set_aspect('equal', adjustable='box')

    plt.grid(False)

    plt.axis('off')

    plt.legend().set_visible(False)

    

    now = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")

    plt.savefig(f"LERW-Full_{N}_{now}.png")


N = 5000

path = random_walk(N)

erased_path = loop_erasure(path)

plot_paths(path, erased_path)