Saturday, January 23, 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 GenerateRandomCodes(double noOfCodes, int codeLength)
        {
            double combinations = MathLibrary.GetCombinations(Characters.Length, codeLength);

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

            List codes = new List();
            for (long i = 0; i < 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 < 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 <= 1) ? 1 : (n * Factorial(n - 1)));
        }
    }

0 comments:

Post a Comment