Generate random non-repeating integers from a small range

后端 未结 5 751
慢半拍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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-10 08:55

    How this?

    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
    
    0 讨论(0)
  • 2020-12-10 08:56

    Taking the idea from A. Donda but fixing the implementation:

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

    The first element of r is a randomly chosen element to start with. The following elements of r randomly choose the difference to the previous element, using modulo arithmetic.

    0 讨论(0)
  • 2020-12-10 08:59

    you can use the following code for generate Non Repeating Random Numbers from 1 to M

    randperm(M);

    and for K Non Repeating Random Numbers from 1 to M

    randperm(M, K);

    enjoy

    0 讨论(0)
提交回复
热议问题