在数组的边框上选择一个随机位置



我已经初始化了一个零数组。我现在想随机选择数组边界的位置。如果位置为0,然后我将其设置为1,而如果是1,则我什么也不做并重复该过程。

这是我目前拥有的:

D = 50 # lattice dims
N = 200 # total number of particles at the end
a = np.zeros((D,D)) # playing board array
# place particle at the center of the board
a[int(D/2), int(D/2)] = 1
border_list = [0, 1, 2, 3]
i = 0
while i < N:
    border = random.choice(border_list)
    pos = math.floor((D)*random.random())
    if border == 0:
        if a[0, pos] == 0:
            a[0, pos] = 1
            i += 1
    if border == 1:
        if a[pos, 0] == 0:
            a[pos, 0] = 1
            i += 1
    if border == 2:
        if a[int(D-1), pos] == 0:
            a[int(D-1), pos] = 1
            i += 1
    if border == 3:
        if a[pos, int(D-1)] == 0:
            a[pos, int(D-1)] = 1
            i += 1

对我来说似乎很低。关于改进的建议吗?

从注释中重写:

almostD = D - 1
choices_for_y = [0, almostD]
i = 0
while i < D:
    x = random.randint(0, almostD)      # anywhere horisontally
    y = random.choice(choices_for_y)    # top or bottom
    if random.random() < 0.5:           # flip x and y in half the cases
        x, y = y, x
    if a[x, y] == 0:
        a[x, y] = 1
        i += 1

但是,请注意,就像您的代码一样,将点放在拐角处而不是沿边缘的机会是两倍。另请注意,这与您的代码相比并不多;少量线。

此代码没有效率问题,可以进行一些改进:

...
while i < N:
    border = random.choice(border_list)
    pos = math.floor((D)*random.random())
    if border == 0 and a[0, pos] == 0:
        a[0, pos] = 1
        i += 1
    elif border == 1 and a[pos, 0] == 0:
        a[pos, 0] = 1
        i += 1
    elif border == 2 and a[int(D-1), pos] == 0:
        a[int(D-1), pos] = 1
        i += 1
    elif border == 3 and a[pos, int(D-1)] == 0:
        a[pos, int(D-1)] = 1
        i += 1

这样,如果if案例之一评估为True,则不会检查以下情况。

最新更新