import numpy as np
import random
import matplotlib.pyplot as plt
tuples_1 = [(x, y) for x in range(1, 101) for y in range(1, 101)]
coordinate = {t: 0 for t in tuples_1}
coordinate[(50,50)] = 1
tuples_2 = [(x, y) for x in (1,100) for y in range(1, 101)]
tuples_3 = [(x, y) for x in range(1,101) for y in (1, 100)]
tuples_4=tuples_2 + tuples_3
boundary = {t: 0 for t in tuples_4}
core = 1
while core <= 999:
item = random.sample(boundary.keys(), 1)
state = boundary.get(item[0])
if state == 1:
continue
if state == 0:
item_list=list(item[0])
x = item_list[0]
y = item_list[1]
print(x, y)
option = np.array([[0, 1], [1, 0], [0, -1], [-1, 0]])
option_r = np.array([[0, 1], [0, -1], [-1, 0]])
option_l = np.array([[0, 1], [0, -1], [1, 0]])
option_u = np.array([[1, 0], [0, -1], [-1, 0]])
option_d = np.array([[0, 1], [1, 0], [-1, 0]])
flag = 0
while flag == 0:
if x == 1:
next_steps = np.random.randint(len(option_l))
x += np.array(option[next_steps])[0]
y += np.array(option[next_steps])[1]
elif x == 100:
next_steps = np.random.randint(len(option_r))
x += np.array(option[next_steps])[0]
y += np.array(option[next_steps])[1]
elif y == 1:
next_steps = np.random.randint(len(option_d))
x += np.array(option[next_steps])[0]
y += np.array(option[next_steps])[1]
elif y == 100:
next_steps = np.random.randint(len(option_u))
x += np.array(option[next_steps])[0]
y += np.array(option[next_steps])[1]
else:
next_steps = np.random.randint(len(option))
x += np.array(option[next_steps])[0]
y += np.array(option[next_steps])[1]
if x>100 or x<1 or y>100 or y<1:
continue
print(x, y)
right = coordinate.get((x+1,y))
right = int(0 if right is None else right)
left = coordinate.get((x-1,y))
left = int(0 if left is None else left)
up = coordinate.get((x,y+1))
up = int(0 if up is None else up)
down = coordinate.get((x,y-1))
down = int(0 if down is None else down)
if right + left + up + down >= 1:
flag = 1
print(x,y)
coordinate[(x, y)] = 1
boundary[(x, y)] = 1
core += 1
x_list, y_list = [], []
for k, v in coordinate.items():
if v == 1:
x_list.append(k[0])
y_list.append(k[1])
plt.scatter(x_list, y_list)
plt.xlim(0, 100)
plt.ylim(0, 100)
plt.xticks()
plt.yticks()
plt.grid(True)
plt.show()
我试图用上述代码模拟 在100100 中 5050的位置有一个激活点
之后的1000次 每次从边界随机选取一个位置放置一个点 点进行随机移动直到周围也有激活点从而使它也被激活
不知道代码哪里出现了问题,每次到了某个点就会停止 我用的pycharm
代码有两个问题。
首先,你在更新坐标点时,有时候会尝试将点移动到超出100*100的边界之外,这可能导致程序停止。你可以在移动之前添加一个条件判断,如果点移动到边界之外,就跳过当前的循环。
其次,你在选择下一个步骤时,使用的是option数组,但是在处理边界情况时,你分别使用了option_r、option_l、option_u、option_d数组。这会导致在某些情况下无法正确处理点的移动方向。你可以在处理边界情况时,使用option数组来确保正确处理点的移动方向。