Link to home
Start Free TrialLog in
Avatar of shragi
shragiFlag for India

asked on

random number generation

I want to generate a 8 digit random number...


the random number is alphanumberic example :"800157c0"

the length of the random number should be just 8 and it can contain either numbers or smaller case alphabets...

Random r = new Random();
            int n = r.Next();
            Console.WriteLine(n);

it gives me random number... how to restrict to 8 digits and how to include smaller case alphabets in the random number....
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Is it required to have alpha characters in it?...or just that it "can" include alphas?
Randomize each digit separately, and then concatenate them together. That will take care of the 8 digits constraint.

For each digit, generate a random value between 0 and 35 (inclusive). If the result is between 0 and 9, use that result as a value. If it is greater than 9, generate a character that has an ASCII/Unicode value that is 87+result.

-----

An easier way would be to generate a big random number, convert it to an hexadecimal value and use that value in a lowercase String that you truncate to 8 characters. The problem with that simpler approach is that the alphabetic characters would be limited form "a" to "f".
Avatar of shragi

ASKER

nothing is required... except the length = 8 ...it can be all numbers or all smaller case alphabets or mixed of both...

ex: abhfgteh
ex: 78634198
ex: 127df423
n.ToString("x8") will work as long as n is an int.
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx explains hex format.

Or are you trying to generate random strings that contain a..z & 0..9?
Give this a shot:
var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
var random = new Random();
var result = new string(
    Enumerable.Repeat(chars, 8)
              .Select(s => s[random.Next(s.Length)])
              .ToArray());

Open in new window

Another simple example:
private Random R = new Random();

        private string GetValue(int length)
        {
            string output = "";
            string allowed = "0123456789abcdefghijklmnopqrstuvwxyz";
            for (int i = 1; i <= length; i++)
            {
                output = output + allowed.Substring(R.Next(allowed.Length), 1);
            }
            return output;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = GetValue(8);
        }

Open in new window

Yet another:
static string GenerateRandomString()
{
    const string CHOICES = "abcdefghijklmnopqrstuvwxyz01234567890";
    StringBuilder result = new StringBuilder(8);
    Random r = new Random();

    while (result.Length != 8)
    {
        int index = Math.Abs((int)(r.NextDouble() * int.MaxValue) % CHOICES.Length);

        System.Threading.Thread.Sleep(5);
        result.Append(CHOICES[index]);
    }

    return result.ToString();
}

Open in new window

Avatar of shragi

ASKER

@disrupt , @kaufmed ,

It worked...

one more ... can we still restrict.... the random number to contain at most three alphabets and  the remaining 5 as integers.... is it possible...
>> "nothing is required... except the length = 8 ...it can be all numbers or all smaller case alphabets or mixed of both..."

...becomes...

>> "can we still restrict.... the random number to contain at most three alphabets and  the remaining 5 as integers...."

What other restrictions will pop up next?

Tell us exactly what you want...in detail.
try this...
protected void Page_Load(object sender, EventArgs e)
        {


            Response.Write(GetStringGen());

        }

        public string GetStringGen()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(RandomString(4, true));
            builder.Append(RandomNumber(1000, 9999));
            return builder.ToString();
        }

        private int RandomNumber(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }

        private string RandomString(int size, bool lowerCase)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowerCase)
                return builder.ToString().ToLower();
            return builder.ToString();
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of disrupt
disrupt
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial