Skip to content Skip to sidebar Skip to footer

How To Generate Unique Random Numbers (that Don't Repeat)?

I'm trying to write a code that randomly chooses numbers and adds them to the list random_numbers, but if a random number was already generated, the code detects that and replaces

Solution 1:

One straightforward way to do non-repeating 'random' (psudeorandom) whole numbers in a modest range is to create a list using range(1, n), then random.shuffle() the list, and then take as many numbers as you want from the list using pop() or a slice.

import random

max = 11
l = list(range(1, max))  # the cast to list is optional in Python 2
random.shuffle(l)

Now every time you want a random number, just l.pop().

Another is to use random.sample() -- see https://docs.python.org/3/library/random.html

Solution 2:

This is one forceful way

import random as rd
random = rd.randint(1,20)
rdlist = []
for _ in range(10):
    whilerandomnotin rdlist:
        rdlist.append(random)
    whilerandomin rdlist:
        random = rd.randint(1,20)

Solution 3:

Randomness is a concept that most people assume means "different every time" or some understanding like that.

In reality, randomness is pretty hard to define and generally, it's safe to assume anyway that you will see repetition. If something is truly random, it (the algorithm) does not care if it repeats or not. It pays no attention to previous values when it creates new ones. This is the gist of what 'random' means in the programming world.

If you roll a die and you get a 4 (1/6 chance), what are the chances you will get a 4 again? It's still 1/6. Getting a 4 once does not change the likelihood of getting it again.

So you don't actually want randomness. You want to somewhat control the behavior of your output.

What I would suggest is keeping another list of integers you have already inserted into the array and if the newest one generated is something you already have, produce another random number in order to hopefully get a different one this time.

Post a Comment for "How To Generate Unique Random Numbers (that Don't Repeat)?"