単純ランダムウォークインスタンス


単純ランダムウォークインスタンス
#       

import numpy as np
import random

# 1.           0,n * m   ,           
#    n = 15, m = 15
mark = np.zeros((15, 15))
# 2.            (currentX, currentY)  
#    currentX = 8, currentY = 8
currentX = 8
currentY = 8
meowCurrent = (currentX, currentY)
# 3.       
# imove[0] = 0;
# jmove[0] = 1; //    
# imove[1] = 1;
# jmove[1] = 1; //    
# imove[2] = 1;
# jmove[2] = 0; //    
# imove[3] = 1;
# jmove[3] = -1; //    
# imove[4] = 0;
# jmove[4] = -1; //    
# imove[5] = -1;
# jmove[5] = -1; //    
# imove[6] = -1;
# jmove[6] = 0; //    
# imove[7] = -1;
# jmove[7] = 1; //    
#              k(0<=k<=7)   
imove = [0, 1, 1, 1, 0, -1, -1, -1]
jmove = [1, 1, 0, -1, -1, -1, 0, 1]
# 4. nextX = currentX + imove[k], nextY = currentY + jmove[k]
# 5.     
num = 0
MAX = 500


#            
def judge_walk():
    return 0 in mark


#     
# global      
def random_walk():
    k = random.randint(0, 7)
    global currentX
    currentX = currentX + imove[k]
    global currentY
    currentY = currentY + jmove[k]


#     
while judge_walk():
    num = num + 1
    if num >= MAX:
        break
    random_walk()
    while currentX > 14 or currentY > 14 or currentX < 0 or currentY < 0:
        random_walk()
    mark[currentX, currentY] = mark[currentX, currentY] + 1
    print(judge_walk())
print(mark)

ブログ参照