Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Random Unique Code

I need to generate a nine digit numeric code (random preferably) which is unique for a given day (same number cannot be generated again on the same day). I was thinking of using HHMMSSmmm (hours, minutes, seconds and milliseconds) to generate the unique code but is not really random. This code generation method can be accessed by multiple methods at the same time so I will have to put a lock on the method. But will this ensure that the number is unique as it is possible that number generation may take less than a millisecond and two threads get the same number?

Is there a better way to generate a random unique numeric code which is unique for a given day? The number of digits can be from 6 to 9 digits.

Edit: The number of random numbers to be generated depends on the number of transactions. Initially the number could be lower but over a period of time it can become very high (multiple transactions per second). Hence, I would not like to compare the number against a used list as this could have performance issues.

Randomness is needed as this number will be entered by the user on the phone. This number is the only way to link the online transaction with the phone transaction so I don't want user to enter a different number by mistake.

The random number generation needs to take place in a ASP.NET MVC application.

like image 241
Achinth Gurkhi Avatar asked May 05 '11 06:05

Achinth Gurkhi


1 Answers

If you start from a random number with 6 digits, then keep adding random, but small enough numbers, you may be abled to do that. You can use the filesystem as the locking storage if you want... but I think you should use a DB for production!

Here is the sample of what I am talking about:

This sample is a console application, that uses a file to control concurrency, and to store the last used number and date it was generated.

If you run it multiple times you will see what happens. Both will have their own unique numbers.

It will NOT store all generated numbers, like you required!

This sample can generate for about 999000 random numbers per day, in the range of 6 and 9 digits inclusive. That is about 11 numbers per second.

using System;
using System.IO;
namespace _5893408
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rand = new Random();
            var futureTime = DateTime.Now.AddSeconds(60);
            while (DateTime.Now < futureTime)
                Console.WriteLine(GetNextNumber(rand));
        }

        public static int GetNextNumber(Random rand)
        {
            var now = DateTime.Now;
            string filePath = @"C:\num.txt";
            FileStream fileStream = null;
            while (fileStream == null)
            {
                try { fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); }
                catch { }
            }
            using (fileStream)
            {
                DateTime date;
                int prevNum;
                if (fileStream.Length == 0)
                {
                    date = now;
                    prevNum = rand.Next(100000, 999999);
                }
                else
                {
                    var reader = new StreamReader(fileStream);
                    {
                        date = DateTime.Parse(reader.ReadLine());
                        prevNum = int.Parse(reader.ReadLine());
                    }
                    if (date.DayOfYear != now.DayOfYear)
                        prevNum = rand.Next(100000, 999999);
                }
                int nextNum = prevNum + rand.Next(10, 1000);
                fileStream.Seek(0, SeekOrigin.Begin);
                using (var writer = new StreamWriter(fileStream))
                {
                    writer.WriteLine(now);
                    writer.WriteLine(nextNum);
                }
                return nextNum;
            }
        }
    }
}

I think that this fulfills your requirements... am I wrong?

If I am, just tell and I'll try to help more.

like image 132
Miguel Angelo Avatar answered Oct 16 '22 05:10

Miguel Angelo