Generating a sequence of random numbers will not be repeated

Questions are as follows:

  Existing n different integers, how randomly selected from m different numbers. (M <= n)

Ideas:

  A random number function mentioned, we immediately think of rand (), this function is used as follows:

  To obtain [a, b) random integer, using the rand ()% (ba) + a;

  To obtain [a, b] of the random integer, using the rand ()% (b-a + 1) + a;

  To obtain (a, b] of the random integer, using the rand ()% (ba) + a +1;

  Spoken official:

    a + rand ()% n, wherein A is a starting value, n being an integer in the range.

  However, rand function alone does not guarantee a random number generated will not be repeated. Online search for a moment, the best method is this:

  1 generates a random number from the number n

  2 is generated from the n-1 remaining number in a random number

  3. Under generated from the remaining n-2 number in a random number

  ..., thus generating m different random number.

  Since each set of operations does not include the random number generated is repeated until the problem does not occur. Code is implemented as follows:

int a[100];
for(i = 0; i < 100; ++i)
    a[i] = i;
for(i = 99; i > 0; --i)
    swap(a[i], a[rand()%(i+1)]);

Reference article:

Fisher–Yates shuffle

 

To shuffle an array a of n elements (indices 0..n-1):
  for i from n − 1 downto 1 do
       j ← random integer such that 0 ≤ j ≤ i
       exchange a[j] and a[i]

 

 

              

 postscript:

Random number is a big problem, the future may have to add content. First posted achieve the following three kinds of under swap:

void swap(int &a, int &b)
{
    int tmp = a;
    a = b;
    b = tmp;
}

void swap(int &a, int &b)
{
    a = a + b;
    b = a - b;
    a = a - b;
}

void swap(int &a, int &b)
{
    a ^= b;
    b ^= a;
    a ^= b;
}
View Code

 

Reproduced in: https: //www.cnblogs.com/gattaca/p/4085281.html

Guess you like

Origin blog.csdn.net/weixin_33918357/article/details/93401831