Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing a subset in uniformly random manner?

Question is:

Write a method to randomly generate a set of m integers from an array of size n. Each element must have equal probability of being chosen.

Is this answer correct?:

I pick a first integer uniformly randomly. pick next. if it already exists. I don't take it else take it. and continue till I have m integers.

like image 363
xyz Avatar asked Jan 19 '23 14:01

xyz


1 Answers

let m be the number of elements to select
for i = 1; i <= m; i++
   pick a random number from 1 to n, call it j
   swap array[j] and array [n] (assuming 1 indexed arrays)
   n-- 

At the end of the loop, the last m elements of array is your random subset. There is a variation on fisher-yates shuffle.

like image 96
frankc Avatar answered Jan 30 '23 22:01

frankc