Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random numbers that are different? [duplicate]

Possible Duplicate:
pick N items at random

I need to generate 6 random numbers between 1 and 49, but they cannot be the same. I know how to do make them random, I just am not sure how to ensure that they are different.

The worksheet recommends displaying each number and setting it to zero, but I don't see how that would help.

Any advice is greatly appreciated.

like image 572
keirbtre Avatar asked Nov 29 '12 15:11

keirbtre


People also ask

How do I generate multiple random numbers in Excel?

To generate multiple random numbers in multiple cells, select the target cells, enter the RANDBETWEEN function, and press control + enter to enter the same formula in all cells at once.

How do you generate random names in Excel without duplicates?

Excel random selection: rows, columns or cells On the Ablebits Tools tab, click Randomize > Select Randomly. Select the range from which you want to pick a sample. On the add-in's pane, do the following: Choose whether you want to select random rows, columns, or cells.


1 Answers

You can use random.sample:

>>> random.sample(xrange(1,50), 6)
[26, 39, 36, 46, 37, 1]

"The worksheet recommends displaying each number and setting it to zero, but I don't see how that would help."

Assuming this is an assignment and you need to implement the sampling yourself, you could take a look at how random.sample is implemented. It's really informative, but may be too complicated for your needs since the code also ensures that all sub-slices will also be valid random sample. For efficiency, it also uses different approaches depending on the population size.

As for the worksheet, I believe it assumes you're starting off with a list of numbers from 1 to 49 and suggests that you replace numbers that you're selected with 0 so there can be skipped if reselected. Here's some pseudo code to get you started:

population = range(1, 50)  # list of numbers from 1 to 49
sample = []
until we get 6 samples:
  index = a random number from 0 to 48  # look up random.randint()
  if population[index] is not 0:  # if we found an unmarked value
    append population[index] to sample
    set population[index] = 0  # mark selected

If you wish to attempt something different, there are many other approaches to consider e.g. randomising the list then truncating, or some form of reservoir sampling.

Good luck with your assignment.

like image 117
Shawn Chin Avatar answered Sep 28 '22 20:09

Shawn Chin