Which of these algorithms is better in performance and order to generate N unique random numbers in the range 1..n?

1

Take an array of n elements: {1, 2, 3, .... n}. Shuffle an array using any of the standard random array shuffling algorithms. The first N elements of the modified array are what you are looking for.

2

Just use Random.Next()in a loop and check if it already exists or not in Dictionaryuntil we have N numbers.

Note that N <n (N is very small than n)

+3
source share
4 answers

Partial Fisher Yates with some settings *:

1000 [0,8000]?

&

?

* , , , , . , N << n ( ). ( O (n/2), , N n.)

- O (N).

, Fisher-Yates, Knuth shuffle.

+1

. -. , . , , .

, ( ), Fisher-Yates - .

dim n[N]                  // gives n[0] through n[N-1]
for each i in 0..N-1:
    n[i] = i              // initialise them to their indexes
nsize = N                 // starting pool size
do N times:
    i = rnd(nsize)        // give a number between 0 and nsize-1
    print n[i]
    nsize = nsize - 1     // these two lines effectively remove the used number
    n[i] = n[nsize]

, , , , .

, , .

, , 10--10:

<------ n[] ------>
0 1 2 3 4 5 6 7 8 9  nsize  rnd(nsize)  output
-------------------  -----  ----------  ------
0 1 2 3 4 5 6 7 8 9     10           4       4
0 1 2 3 9 5 6 7 8        9           7       7
0 1 2 3 9 5 6 8          8           2       2
0 1 8 3 9 5 6            7           6       6
0 1 8 3 9 5              6           0       0
5 1 8 3 9                5           2       8
5 1 9 3                  4           1       1
5 3 9                    3           0       5
9 3                      2           1       3
9                        1           0       9

, , , , , .

+2

(n N).

n N (, ), . , , , ... N ; , (, O (m), m); , - , , .

n N (, 99 ), ( , , ) . Fisher-Yates shuffle, O (n).

:

  • , n N,
  • , n, " ", N,
  • , ,
  • If I don’t know the values ​​ahead of time, I’d run two options on many different (n, N) pairs several times to try to better understand how to work out a balance,
+2
source

In the worst case, 2 may never end, since each number that it creates may already be on the list. However, in the general case, you will iterate much more than N numbers.

1 is completed in a finite time.

0
source

Source: https://habr.com/ru/post/1777349/


All Articles