Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to generate random number of size X

In my mobile application I have to provide the user with a random unique X alphanumeric code so that the user can reply with that alphanumeric code to perform some task.

The number of users going to use this application is around 1 million people and the message traffic is around 0.1 million messages/day.

I can use only 26 upper letters, 26 lower letters and 10 digits. If the random number size is 5 then I can generate 916132832 unique combinations. After the combinations get exhausted I want to recycle this number generation again.

I am looking for an algorithmic approach. Is there any algorithmic approach to solve this problem?

like image 777
Dungeon Hunter Avatar asked Aug 24 '11 08:08

Dungeon Hunter


1 Answers

If you accept to recycle the random numbers, why do you want to wait for the exhaustion of the combinations before recycling?

  • This makes the numbers less and less random when going to the end of the combination set
  • This forces you to maintain some database to know which numbers have already been used and which haven't.

I would just generate random numbers, without caring if they've been used already.

If you really really want to keep it like you asked, here's how you could do it:

  • Generate all the combinations and put them into a database table
  • Store the size of this table in some variable
  • Generate a random number R between 1 and the size of the table
  • Fetch the combination stored at the Rth row of the table
  • Delete the Rth row from the table, and decrement the size variable
  • when the table is empty (and the size variable is 0), start again

You could improve it by moving the used numbers from one table to another, and use the second table instead of the first one when the first table is empty.

You could also do that in memory, if you have enough of it.

like image 199
JB Nizet Avatar answered Sep 30 '22 09:09

JB Nizet