Love Bisaria
Love Bisaria

Reputation: 167

Generate m random numbers out of a given array of n numbers

I have one doubt. Does creating random set m integers out of n array elements means that all the m elements have to be unique, because the probability of selecting each number is equal.

For example, If I have original array as {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} (n = 10) and I am selecting 5 elements(m = 5) randomly. So does that mean that {1, 1, 5, 7, 9} is an unacceptable solution because 1 has occurred twice.

Upvotes: 2

Views: 1911

Answers (3)

Mukul Jain
Mukul Jain

Reputation: 21

A short answer to your question is NO. Selecting means choosing an element ( not copying/replicating) from a given set and by doing so we are not allowed to change the original set. m elements don't have to be unique but the original element set ( Space ) should remain unchanged.

Upvotes: 0

user3821934
user3821934

Reputation:

If you really are selecting randomly from an array, then each selection might be the same element, so a procedure that tried to build a set of m elements from an array of n elements (where n>=m) might never terminate. For example, it might just pick the same element over and over, thus never increasing the size of the set of selected elements.

Upvotes: 0

noMAD
noMAD

Reputation: 7844

I think that depends on the use case. The normal way to get random numbers is by using Fisher-Yates algorithm. So basically you pick a number and then move that number to the end of the array and reduce the size of the array by 1 so that the next number you choose doesn't repeat.

Basic pseudo code:

  for i from n − 1 downto 1 do
       j ← random integer with 0 ≤ j ≤ i
       exchange a[j] and a[i]

Upvotes: 0

Related Questions