如何在不重复两个连续元素的情况下重新排列数字数组? [英] How to shuffle an array of numbers without two consecutive elements repeating?

查看:80
本文介绍了如何在不重复两个连续元素的情况下重新排列数字数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试随机获取这样的数字数组:

I'm currently trying to get an array of numbers like this one randomly shuffled:

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

唯一的约束是改组中没有连续的元素必须是相同的数字。为此,我当前正在使用以下代码:

The only constrain is that no consecutive elements of the shuffle must be the same number. For that I'm currently using this code:

# 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)

虽然这适用于这种大小的数组,我不知道它是否适用于更大的数组。即使这样,它仍可能会花费很多时间。

Although this works for an array of this size, I don't know if it would work for much bigger arrays. And even so, it may take a lot of time.

因此,有没有更好的方法?

So, is there a better way of doing this?

推荐答案

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

May not be technically the best answer, hopefully it suffices for your requirements.

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)

这篇关于如何在不重复两个连续元素的情况下重新排列数字数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆