从小范围生成随机非重复整数

时间:2013-10-28 19:49:04

标签: matlab random

我想要完成的是以下内容:

我希望从相对较小的范围创建一个整数向量,并确保所有整数都不会跟随相同的整数。

即,这是一个“合法”的载体: [1 3 4 2 5 3 2 3 5 4]

这是一个“非法”向量(因为5跟随5): [1 3 4 2 5 5 2 3 5 4]

我已尝试使用randirandperm的各种变体,当我尝试从小范围生成大约100个元素的向量时,我总是陷入困境(即, 1到5之间的整数。

该功能运行时间过长。

这是我做过的一次尝试:

function result = nonRepeatingRand(top, count)

    result = randi(top, 1, count);

    while any(diff(result) == 0)
         result = randi(top, 1, count);    
    end

end

非常感谢任何和所有帮助。谢谢!

6 个答案:

答案 0 :(得分:11)

您可以通过从1top - 1生成差异,然后计算累积和模数来定义您要查找的序列类型top,从随机初始值开始:

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万个数字的非重复序列。

答案 1 :(得分:2)

您可以使用以下代码生成1到M的非重复随机数

  
    

randperm(M);

  

和K非重复随机数从1到M

  
    

randperm(M,K);

  

享受

答案 2 :(得分:1)

不要每次都重新生成序列,而是修复重复。 E.g:

function result = nonRepeatingRand(top, count)

    result = randi(top, 1, count);

    ind = (diff(result) == 0);
    while any(ind)
        result(ind) = [];
        result(end + 1 : count) = randi(top, 1, count - numel(result));

        ind = (diff(result) == 0);
    end

end

在我的机器上,这会在1.6秒内从1:5生成1000万个数字的非重复序列。

答案 3 :(得分:1)

采纳A. Donda的想法,但修正了实现方式:

r=[randi(top,1,1),randi(top - 1, 1, count-1)];
d=rem(cumsum(r)-1,top)+1;

r的第一个元素是一个随机选择的元素。 r的以下元素使用模运算随机选择与前一个元素的差。

答案 4 :(得分:0)

这是怎么回事?

top = 5;
count = 100;
n1 = nan;
out = [];
for t = 1: count 
    n2 = randi(top);
    while n1 == n2
        n2 = randi(top);
    end
    out = [out, n2];
    n1 = n2;
end

答案 5 :(得分:0)

是否有可能选择创建这个“随机”序列而不重复,以便所有值均匀分布(与randperm一样)?

randperm似乎有限,我只能想到在while循环中调用第一个函数,直到我的“相等分布critereon”得到满足......但它可以更快地完成吗?