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 > combinations)
throw new Exception(String.Format("noOfCodes > maximum combinations. I.e. noOfCodes > {0}", combinations));
List<string> codes = new List<string>();
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)));
}
}
No comments:
Post a Comment