OneCompiler

Random walker algorithm

97

Random Walker

Following is code for simple random walker algorithm.

import numpy
from random import choice, randrange
from typing import Tuple, List

def random_walker(grid_size: Tuple[int, int]):
  array = numpy.full(shape=grid_size, fill_value=0, dtype=int)
  row, col = start = (0, 0)
  all_directions = [0, 1, 2, 3]
  row, col = (0, 0)
  
  for i in range(0, 26):
    array[row][col] = 97 + i
    
    no_move = True


    temp_dirs = all_directions.copy()
    while len(temp_dirs) > 0:
      d = choice(temp_dirs)
      
      if d == 0 and row - 1 >= 0 and array[row-1][col] == 0:
        row = row - 1
        no_move = False
        break
      elif d == 1 and col + 1 < len(array[0]) and array[row][col + 1] == 0:
        col = col + 1
        no_move = False
        break
      elif d == 2 and row + 1 < len(array) and array[row + 1][col] == 0:
        row = row + 1
        no_move = False
        break
      elif d == 3 and col-1 >= 0 and array[row][col - 1] == 0:
        col = col - 1
        no_move = False
        break
      temp_dirs.remove(d)
    
    if no_move:
      break
  
  return array

res = random_walker((10, 10))
print(res)