Programming Algorithm

Generate random not repeatable values

Yurii Kuznietsov
Sep 3, 2020 · 3 min read

Finding an algorithm with the best performance

Generating random values sounds like a simple task, if we go deeper we will find out that it is not so simple.

Solution 1

The simple solution to our issue is to create random numbers. After that we always need to check the new number, if the number is unique we add if not generate new and check again.

In this case can generate a maximum of 50 random numbers, if we need to generate around 40 random numbers we have the issue. Our algorithm is just guessing what number we do not have. We will generate the same number over and over again that is already in the collection.

Solution 2

Another approach is to create a list of possible numbers, and remove numbers that you pick from the list:

This algorithm is better because we are not guessing. We are getting a unique number and removing that number from the collection.

On each call, we are generating a new collection of values. What if we do not need to do it? What if we can generate a collection of values only one time?

Solution 2

Instead of removing items, we can change their location in the collection.

The idea is simple: we generate a random index, we take an item by index after that we change the location of the item. The current item became last, last became current. We are just a little shuffling our collection.

We also need to make the range smaller for generating a random index.

The last approach will show the best performance because we are not creating a new collection and do not change its size.

If you need to take a close look at the project here is the link.

Originally published at http://tomorrowmeannever.com on September 3, 2020.

Geek Culture

Proud to geek out. Follow to join our +1M monthly readers.