在一定范围内并以最小的距离创建整数的随机序列 [英] Create random sequence of integers within a range and with a minimum distance between them

查看:67
本文介绍了在一定范围内并以最小的距离创建整数的随机序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

生成特定nr个随机值整数的最快方法是什么?该整数均匀分布在特定范围内,并且每个元素之间的距离最短?

What is the fastest way to generate a specific nr of integers of random value uniformly distributed within a specific range and with a minimum distance between each element?

例如,给定一个介于0到20之间的序列范围,我们想要创建5个元素,每个元素之间的距离至少为3点,结果可能是这样的[0,5,11,14,19][2,5,9,13,18]

For example, given a sequence range between 0 and 20, we want to create 5 elements with at least 3 points distance between each element, the result could be something like this [0,5,11,14,19] or [2,5,9,13,18]

我创建了一个可以达到此目的的循环,但是当我要创建数百万个范围时,速度非常慢.

I created a loop that achieves this but it is very slow when i want to create ranges in the order of millions.

推荐答案

如何处理以下食谱:如果您希望相邻的5个元素之间的间距为3,但总范围为20,则您实际上拥有松弛"步骤,您可以在元素之间的间隙中随机分布.假设我们生成一个在该范围内的数字,并将其分散在元素之间,然后最终得到类似以下的代码:

How about the following recipe: If you want a gap of 3 between your 5 adjacent elements, but want a total range of 20, then you effectively have 20 - (5-1)*3 steps of "slack" that you can randomly distribute in the gaps between your elements. Suppose we generate a number in that range, and scatter it between the elements, then we end up with code something like the following:

import numpy, random

n = 5
limit = 20
mingap = 3

slack = 20 - mingap * (n - 1)

def generate():
    steps = random.randint(0, slack)

    increments = numpy.hstack([numpy.ones((steps,)), numpy.zeros((n,))])
    numpy.random.shuffle(increments)

    locs = numpy.argwhere(increments == 0).flatten()
    return numpy.cumsum(increments)[locs] + mingap * numpy.arange(0, n)

如果您随后调用此generate()函数十次,您将获得类似于以下内容的向量集合:

If you then invoke this generate() function ten times, you get a collection of vectors something like the following:

[  0.   3.   6.   9.  12.]
[  0.   3.   6.  10.  13.]
[  2.   5.   8.  12.  15.]
[  1.   4.   7.  12.  16.]
[  0.   4.   7.  10.  13.]
[  0.   3.   6.   9.  12.]
[  1.   4.   9.  12.  16.]
[  0.   7.  10.  13.  16.]
[  0.   5.   8.  11.  14.]
[  1.   4.   8.  11.  17.]

这篇关于在一定范围内并以最小的距离创建整数的随机序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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