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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With