Fisher-Yates Shuffle: random if it is stopped m times?

I have integers 1,2,3, ..., n, from which I have to select m <n different integers randomly. I intend to put these integers in an array, and then use the Fisher Yates Shuffle:

Randomly select an entry in the array. Change it to the last entry. Then randomly select an entry in the array, with the exception of the last entry. Change this to the second last record. Repeat until the last m records are received.

Question

My understanding is that if you continue up to n times, each possible layout is equally likely with this shuffle. Thus, if you stop after m <n times, each individual layout of the last m records is equally likely. Therefore, the last m entries are m random different integers that I need.

Do I understand correctly?

+4
source share
1 answer

Yes, it may be easier to go forward:

Let rand(z) return in the range [0..z)

 for (int i = 0; i < m; i++) swap(X[i], X[i+rand(ni)]) 

X[0..m-1] now a random sample

+3
source

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


All Articles