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.
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.
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.
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.
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