Saturday 23 January 2010

Random Code Generator in C#

I needed to generate a whole bunch of random codes so I wrote a little class to do it for me. Here is the code for it

public class CodeGenerator
    {
        private const string Characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890$-_.+!*'(),";
        private Random m_Random;
        
        public CodeGenerator()
        {
            m_Random = new Random();
        }

        public List<string> GenerateRandomCodes(double noOfCodes, int codeLength)
        {
            double combinations = MathLibrary.GetCombinations(Characters.Length, codeLength);

            // check permutations
            if (noOfCodes &gt; combinations)
                throw new Exception(String.Format("noOfCodes &gt; maximum combinations. I.e. noOfCodes &gt; {0}", combinations));

            List<string> codes = new List<string>();
            for (long i = 0; i &lt; noOfCodes; )
            {
                string code = GenerateCode(codeLength);
                if (!codes.Contains(code))
                {
                    codes.Add(code);
                    i++;
                }
            }
            return codes;
        }

        public string GenerateRandomCode(int codeLength)
        {
            return GenerateCode(codeLength);
        }

        private string GenerateCode(int codeLength)
        {
            string code = "";

            // select random character 
            for (int i = 0; i &lt; codeLength; i++)
                code += Characters[m_Random.Next(Characters.Count())];

            return code;
        }
    }


Oh and my Math Library

public class MathLibrary
    {
        public static double GetCombinations(int n, int k)
        {
            double top = Factorial(n + k - 1);
            double bottomLeft = Factorial(k);
            double bottomRight = Factorial(n - 1);

            return (double)top / (bottomLeft * bottomRight);
        }

        public static double Factorial(int n)
        {
            return ((n &lt;= 1) ? 1 : (n * Factorial(n - 1)));
        }
    }

No comments:

Post a Comment