Generate random non-repeating integers from a small range

后端 未结 5 766
慢半拍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:35

    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
    

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

提交回复
热议问题