2

I have a method which generates the Coupon Code. Can anyone help/ suggest to generate ALPHANUMERIC CODE?

Following is the method:

public string CouponGenerator(int length)
    {
        var sb = new StringBuilder();
        for (var i = 0; i < length; i++)
        {
            var ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * _random.NextDouble() + 65)));

            sb.Append(ch);
        }

        return sb.ToString();
    }
    private static readonly Random _random = new Random();

Example:

UZWKXQML when Lenght is set to 8

But it need something like U6WK8Q2L i.e Alphanumeric code.

SHEKHAR SHETE
  • 5,964
  • 15
  • 85
  • 143
  • See [How can I generate random alphanumeric strings in C#?](http://stackoverflow.com/questions/1344221/how-can-i-generate-random-alphanumeric-strings-in-c) – CodesInChaos Oct 30 '14 at 22:30

2 Answers2

6

You can change the length of Coupan code.

 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var random = new Random();
    var result = new string(
        Enumerable.Repeat(chars, 8)
                  .Select(s => s[random.Next(s.Length)])
                  .ToArray());
Kumod Singh
  • 2,113
  • 1
  • 16
  • 18
0

Just shuffle sequency of alpha bet and take number of chars that you need.

   public string CouponGenerator(int length, char[] alphaNumSeed)
    {
        var coupon = alphaNumSeed.OrderBy(o => Guid.NewGuid()).Take(length);

        return new string(coupon.ToArray());
    }
Andrei
  • 1
  • 1
  • 1) While `NewGuid` is random in the current implementation, it's not guaranteed to be random. 2) Why do you prevent duplicate characters? – CodesInChaos Oct 30 '14 at 22:32
  • It's just a tricky thing to shuffle char array. And as i know GUID use pseudo-random algorithm, which actually is quite ok, when we are talking about random sequences – Andrei Oct 31 '14 at 04:40