I have a random walking code that works sometimes.
The algorithm just uses base Python to print a matrix on the terminal; the walk increments every cell it steps on, and it does just that. The one problem is that sometimes it does one less step (or more) than it should. It should stop when the step_count is equal to max_steps, but it only does that occasionally.
Here is a random walking algorithm that I made. I've tried removing the minus 1 from the max steps on the while loop, but that just makes the step go from 99–100 to 100–101. I've also tried adding another if-then break inside the while loop, but nope.
import random
def walking(dimension):
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] # cardinal directions: Up Down Right Left
path=[]
# randomizes the starting point. because that's more interesting
start = (random.randint(0, dimension), random.randint(0, dimension))
path.append(start)
max_steps = 100 # can change to desired step amount
step_count = 0
while step_count < max_steps-1:
x, y = path[-1]
moves = []
for dx, dy in directions:
new_spot = (x + dx, y + dy)
moves.append(new_spot)
next_pos = random.choice(moves)
if 0 <= next_pos[0] < dimension and 0 <= next_pos[1] < dimension:
path.append(next_pos)
step_count += 1
return path
grid_size = 5 # can change to desired grid size
grid = [[0] * grid_size for _ in range(grid_size)]
walk = walking(grid_size)
for step in walk:
x, y = step
if 0 <= x < grid_size and 0 <= y < grid_size:
grid[x][y] += 1 # this increments the cell its on
# calculates the summation of the entire matrix.
total_sum = sum(sum(row) for row in grid)
# prints the updated grid and the summation which is equal the amount of steps
for row in grid:
print('\t'.join(map(str, row)))
print("Steps taken:", total_sum)