从小范围生成随机的非重复整数 [英] Generate random non-repeating integers from a small range
问题描述
我要完成的工作如下:
我希望创建一个相对较小范围的整数向量,并确保所有整数都不会跟在同一整数之后.
I wish to create a vector of integers, from a relatively small range, and ensure that none of the integers will be followed by the same integer.
即,这是一个合法"载体: [1 3 4 2 5 3 2 3 5 4]
i.e., This is a "legal" vector: [ 1 3 4 2 5 3 2 3 5 4 ]
,这是一个非法"向量(因为5后接5): [1 3 4 2 5 5 2 3 5 4]
and this is an "illegal" vector (since 5 follows 5): [ 1 3 4 2 5 5 2 3 5 4 ]
我已经尝试了randi
,并尝试了randperm
的各种变化形式,当我尝试从一个很小的范围(即1到1之间的整数)生成一个大约100个元素的向量时,我总是会卡住5).
I've experimented with randi
, and all sorts of variations with randperm
, and I always get stuck when i try to generate a vector of around 100 elements, from a small range (i.e., integers between 1 and 5).
该函数运行时间过长.
这是我所做的尝试之一:
Here's one of the attempts that i've made:
function result = nonRepeatingRand(top, count)
result = randi(top, 1, count);
while any(diff(result) == 0)
result = randi(top, 1, count);
end
end
任何人和所有帮助将不胜感激.谢谢!
Any and all help will be much appreciated. Thanks !
推荐答案
可以通过生成从1
到top - 1
的差异,然后计算从一个随机初始值开始的累积总和模量 top
:
The kind of sequence you are looking for can be defined by generating differences from 1
to top - 1
and then computing the cumulative sum modulus top
, starting from a random initial value:
function result = nonRepeatingRand(top, count)
diff = randi(top - 1, 1, count);
result = rem(cumsum(diff) + randi(1, 1, count) - 1, top) + 1;
end
在我的机器上,这会在0.58秒内以1:5的形式生成1000万个数字的非重复序列.
On my machine, this generates a non-repeating sequence of 10 million numbers out of 1:5 in 0.58 seconds.
这篇关于从小范围生成随机的非重复整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!