Numpy数组项顺序 - 序列的相等分布

时间:2015-10-21 23:47:01

标签: python algorithm numpy random graph-theory

假设我有一个洗牌的numpy数组:

a = np.array([1,2,3,4,5,6]*6)
np.random.shuffle(a)

如何确保混洗数组中的每个项目彼此跟随相同的次数?

例如,我想确保数字1跟随数字2中的数字2跟随数字4的次数相同。同样适用于所有其他数字

我们可以假设这个问题的列表是循环的,即第一个项目跟在最后一个

之后

通常情况下,我会发布一些我尝试过的代码,但是在谈到这一点时我感到很茫然。

我能想到的最低效的方法是编写一个函数,计算一个数字跟随另一个数字的次数,然后检查所有计数是否相等。如果没有,重新洗牌。

但这并不能保证我最终会得到一个符合平等分配标准的列表。

1 个答案:

答案 0 :(得分:3)

这是我能想到的最好的。请注意,对于36个数字,每个数字必须恰好跟随一个数字。

while True:
    x = {i: set(range(1,7)) for i in range(1,7)}

    a = [random.choice(range(1,7))]  # start with a random number
    last = a[-1]
    while x[last]:
        next = random.choice(list(x[last]))
        x[last].remove(next)
        a.append(next)
        last = next

    if len(a) == 37:
        # We get to length 37 if and only if each set above is exhausted.
        # In this case, the first item will always equal the last item
        # (proof left as an exercise for the reader), so remove it.
        a = a[:-1]
        break

print(''.join(str(i) for i in a))

对我来说,产生221164425231355145433465615366263241似乎符合标准。