Previously, I wrote a random_n Algorithm Implementation. Although it is easy to understand, the algorithm efficiency is not very high. It saves space and is only implemented by pulling an array.
This random_n implementation uses to pull two arrays, And the arrays in the sub-function release space when the function stack is destroyed. The best and worst run times are O (N ). It is mainly used to pull space for time.
The Code is as follows:
# Include <stdio. h>
# Include <stdlib. h>
# Define MAX_NUM 10
Void random_n (int a [], int n );
Int main ()
{
Int a [MAX_NUM], I = 0, j = 0;
While (j <MAX_NUM)
{
A [j] =-1;
J ++;
}
Random_n (a, MAX_NUM );
While (I <MAX_NUM)
{
Printf ("% d \ t", a [I]);
I ++;
}
Printf ("\ n ");
Return 0;
}
Void random_n (int a [], int n)
{
Int temp [n], k = 0, count = 0, x = 0;
While (k <n)
{
Temp [k] = k;
K ++;
}
Srand (time (0 ));
Count = n;
K = 0;
While (count)
{
X = rand () % count;
A [k] = temp [x];
Printf ("X = % d \ t temp = % d \ n", x, a [k]);
Temp [x] = temp [count];
Count = count-1;
K = k + 1;
X = 0;
}
}
Debugging and running results:
The main idea is to first generate all numbers between 0 and N, then generate a random number in sequence, and use the generated random number as the subscript to access the generated ordered array, take out the values corresponding to the following table and pay them to the passed meta array. Then overwrite the number with the last data. Then, subtract 1 from the modulo that generates the random number, so that the valid range of the next access is not previously accessed. In this way, the array is filled in cyclically.
The thought process is as follows:
----------------------------------------------------------------------------------------------
| 0 | 1 | 2 | .... |... | N-1 | N |
Bytes -----------------------------------------------------------------------------------------------
If the random number is 2, then:
Bytes ----------------------------------------------------------------------------------------------
| 0 | 1 | N | .... |... | N-1 | N |
Bytes -----------------------------------------------------------------------------------------------
The next addressing range is:
Bytes ----------------------------------------------------------------------------------------------
| 0 | 1 | 2 | .... |... | N-1 | N |
Bytes -----------------------------------------------------------------------------------------------
In turn.
From Mingyue Tianya