Generate random non-repeating integers from a small range

后端 未结 5 749
慢半拍i
慢半拍i 2020-12-10 08:16

What I\'m trying to accomplish is the following:

I wish to create a vector of integers, from a relatively small range, and ensure that none of the integers will be f

5条回答
  •  时光说笑
    2020-12-10 08:51

    Do not regenerate the sequence every time, but fix the repetitions. 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
    

    On my machine, this generates a non-repeating sequence of 10 million numbers out of 1:5 in 1.6 seconds.

提交回复
热议问题