I would like to generate random numbers in the range (0..."MAX"). I would like to make a loop such that every time going through the loop a new unique random number is generated (should not repeat). The loop will continue a total of "MAX" times. There should be "MAX" number of random numbers generated in total. When sorted, the values should be 0..."MAX"; no repetition.
Restrictions: - Assume MAX is much larger than int. (no memory to store all number permutations in memory)
My proposed solution: If I seed the generator from 0...MAX would that allow me to print every unique number between 0 and MAX as in the below function? Assume there's no space to store all numbers and shuffling them.
for x in range (0, MAX):
random.seed(x)
num=random.randint(0, MAX)
print("seed = ",x, " random number = ", num)
If the answer for the above is yes then would this generation be reversible (can i get the seed from the random number)? In which case would this be considered a kind of block cipher that is if the seed (key) and the range is the same length?
If you want to get all the numbers within a particular range,
either we have to store the generated random numbers and compare them against the newly generated random number
or we can generate the list and shuffle it like this
since you already have the population as a list and
random.shuffle
is an in-place operation, the result doesn't have to be stored in a separate list.You can do like this:
with in the range of x and y it will select some random values. W/o repetition means you can use set. so i am adding those values to set.
just make a try this one.
The random module has a sample function, which is predicated on producing
unique elements
. It is used as in the following example:But, do be aware that it will throw an exception if the length of the list is greater than the size of the population, e.g.