Generate unique random integers
Generating unique random integers is an important task in various domains. Examples include data sampling, simulations, and even lottery picks. Products have come a long way from when one had to write a fair amount of code to do the needful. Below are two solutions, one in MS Excel and the other in Python.
Suppose we want 6 random numbers from the range 1 to 54. Here the population is the list of 54 integers between 1 and 54 and the sample size is 6.
The intuitive way to do pick random numbers is to repeatedly generate numbers between 1 and 54 and check that it is not already selected . However, this gets extremely wasteful as the sample size approaches the population size. Imagine the extreme case where we want to pick 54 random numbers between 1 and 54. There's nothing random about the last pick. So, repeatedly generating a number between 1 and 54 and checking if it is already selected is...well, wasteful.
It's easier to sort the list of 54 numbers in random order and pick the top 6.
In Excel, the below function does the needful:
=LAMBDA(_Min,_Max,_NbrVals,
? ? LET(_Range,_Max-_Min+1,
? ? ? ? INDEX(SORTBY(SEQUENCE(_Range,,_Min),RANDARRAY(_Range)),SEQUENCE(_NbrVals))
? ? ? ? ))
领英推荐
How does it work?
Of course, even better would be if we had a function that did the needful for us. And, in Python, random.sample does just that.
import random
print(random.sample(range(1, 54+1),k=6))
[47, 20, 54, 38, 41, 12]
For more on this function see random — Generate pseudo-random numbers — Python 3.11.1 documentation
Do you have occasion to generate unique random integers? How do you do so?
My previous post: MS Excel: Goal Seek or Algebra | LinkedIn
Microsoft MVP (Excel)
2 年Here is a LinkedIn article I wrote which includes a VBA function that iterates its loop only as many times as unique random numbers requested (for example, it only loops 6 times to produce 6 unique random numbers). Note the first 2/3s or so of code is devoted to "house-keeping" chores... the juicy part of the code is in the last For..Next loop... www.dhirubhai.net/pulse/get-random-number-unique-items-from-array-rick-rothstein/