【问题标题】:How to shuffle an array of numbers without two consecutive elements repeating?如何在没有两个连续元素重复的情况下打乱一个数字数组?
【发布时间】:2019-03-03 12:10:32
【问题描述】:

我目前正在尝试获取一组随机随机排列的数字:

label_array = np.repeat(np.arange(6), 12)

唯一的限制是随机播放的连续元素不能是相同的数字。为此,我目前正在使用此代码:

# Check if there are any occurrences of two consecutive 
# elements being of the same category (same number)
num_occurrences = np.sum(np.diff(label_array) == 0)

# While there are any occurrences of this...
while num_occurrences != 0:
    # ...shuffle the array...
    np.random.shuffle(label_array)

    # ...create a flag for occurrences...
    flag = np.hstack(([False], np.diff(label_array) == 0))
    flag_array = label_array[flag]

    # ...and shuffle them.
    np.random.shuffle(flag_array)

    # Then re-assign them to the original array...
    label_array[flag] = flag_array

    # ...and check the number of occurrences again.
    num_occurrences = np.sum(np.diff(label_array) == 0)

虽然这适用于这种大小的数组,但我不知道它是否适用于更大的数组。即便如此,也可能需要很长时间。

那么,有没有更好的方法呢?

【问题讨论】:

标签: python arrays numpy random


【解决方案1】:

在技术上可能不是最佳答案,希望它足以满足您的要求。

import numpy as np
def generate_random_array(block_length, block_count):
    for blocks in range(0, block_count):
        nums = np.arange(block_length)
        np.random.shuffle(nums)
        try:
            if nums[0] == randoms_array [-1]:
                nums[0], nums[-1] = nums[-1], nums[0]
        except NameError:
            randoms_array = []
        randoms_array.extend(nums)
    return randoms_array


generate_random_array(block_length=1000, block_count=1000)

【讨论】:

  • 这绝对是个好主意。唯一的问题是样本的分布将包含在每个子集中,这对于该函数的某些应用程序来说可能是一个问题。在我的例子中,这是为了随机化行为实验的刺激类别,所以这很有效,而且对于非常长的列表也运行得非常快。
【解决方案2】:

这是一种方法,对于 Python >= 3.6,使用 random.choices,它允许从具有权重的总体中进行选择。

这个想法是一个一个地生成数字。每次我们生成一个新数字时,我们都会通过暂时将其权重设置为零来排除前一个数字。然后,我们减少所选择的权重。

正如@roganjosh 适当指出的那样,当我们留下多个最后一个值的实例时,我们最后会遇到问题 - 这可能非常频繁,尤其是在少量值和大量重复的情况下.

我使用的解决方案是使用简短的send_back 函数将这些值重新插入到不会产生冲突的列表中。

import random

def send_back(value, number, lst):
    idx = len(lst)-2
    for _ in range(number):
        while lst[idx] == value or lst[idx-1] == value:
            idx -= 1
        lst.insert(idx, value)


def shuffle_without_doubles(nb_values, repeats):
    population = list(range(nb_values))
    weights = [repeats] * nb_values
    out = []
    prev = None
    for i in range(nb_values * repeats):
        if prev is not None:
            # remove prev from the list of possible choices
            # by turning its weight temporarily to zero
            old_weight = weights[prev]
            weights[prev] = 0    

        try:
            chosen = random.choices(population, weights)[0]
        except IndexError:
            # We are here because all of our weights are 0,
            # which means that all is left to choose from
            # is old_weight times the previous value
            send_back(prev, old_weight, out)
            break

        out.append(chosen)
        weights[chosen] -= 1
        if prev is not None:
            # restore weight
            weights[prev] = old_weight
        prev = chosen
    return out

print(shuffle_without_doubles(6, 12))

[5, 1, 3, 4, 3, 2, 1, 5, 3, 5, 2, 0, 5, 4, 3, 4, 5,
 3, 4, 0, 4, 1, 0, 1, 5, 3, 0, 2, 3, 4, 1, 2, 4, 1,
 0, 2, 0, 2, 5, 0, 2, 1, 0, 5, 2, 0, 5, 0, 3, 2, 1,
 2, 1, 5, 1, 3, 5, 4, 2, 4, 0, 4, 2, 4, 0, 1, 3, 4,
 5, 3, 1, 3]

一些粗略的时间:生成(shuffle_without_doubles(600, 1200))大约需要30秒,所以有720000个值。

【讨论】:

  • 这与我正在处理的非常相似,但是您可能会在最后几个选择中失败,不是吗?一旦接近尾声,您可能没有可行的选择
  • @roganjosh 我不明白为什么。权重的总和始终等于我们仍然必须生成的值的数量,并且只有我们可以选择的那些具有非零权重。例如,对于最终值,权重类似于 [0, 0, 0, 1, 0, 0],因此我们确信会选择 3。我错过了什么吗?
  • 因为理论上,您可以在最后放置 3 个 0 值?这是一个随机分布,例如,当您填写最后一个索引时,保证倒数第二个值与您留下的值不同?我的偶尔会失败。
  • 是的,它失败了。刚刚用IndexError 让你的函数在我身上崩溃了两次。这个不行,需要反复运行。
  • 你说得对,我错过了那个。在这种情况下,我所有的权重都为 0,random.choices 将失败并返回 IndexError。我会考虑如何防止这种情况......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-21
相关资源
最近更新 更多