random number generation

shragi
shragi used Ask the Experts™
on
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....
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009

Commented:
Is it required to have alpha characters in it?...or just that it "can" include alphas?
Top Expert 2015

Commented:
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".

Author

Commented:
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

Commented:
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?

Commented:
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

Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009

Commented:
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

kaufmedGlanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
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

Author

Commented:
@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...
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009

Commented:
>> "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.

Commented:
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

Commented:
also if you want to randomize the string use this:
protected void Page_Load(object sender, EventArgs e)
        {

            Random num = new Random();

            string rand = new string(GetStringGen().ToCharArray().
        OrderBy(s => (num.Next(2) % 2) == 0).ToArray());

            Response.Write(rand);

        }

        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

kaufmedGlanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
Mine could be modified as such:
static string GenerateRandomString()
{
    const string CHOICES = "b97jumekvn0pf5xtw6ygqc0irz1d23sa8hol4";
    StringBuilder result = new StringBuilder(8);
    Random r = new Random();
    int letterCount = 0;
    int index = 0;

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

            if (char.IsLetter(CHOICES[index]))
            {
                letterCount++;
            }
            else
            {
                break;
            }
        }
        while (letterCount >= 3);

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

    return result.ToString();
}

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial