Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate random sequence of AlphaNumeric

I want a code to generate sequence of Alphanumeric character like LLNNLLNNLL where L is the Letter and N is the number. For example if the length is 5 the sequence will be LLNNL and if the length is 6 the sequence will be LLNNLL and if 7 it would be LLNNLLN.

string alphabets = "ABCDEFGHIJKLMNPQRSTUVWX";
int length = model.VALUE_INT;
string result = "";
for (int i = 0; i < length; i++)
{
    int next = _random.Next(23);
    result += alphabets.ElementAt(next);
    result += _randomNum.Next(1, 9);
}

This is what I have tried but condition is not fulfilling

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For each position (value of i) of your output string you need to check if you need a character or an integer.
Since the pattern repeats every 4 positions, you can achieve this using the modulo operator:

for (int i = 0; i < length; i++)
{
    switch (i % 4)
    {
        case 0:
        case 1:
            int next = _random.Next(23);
            result += alphabets.ElementAt(next);
            break;

        case 2:
        case 3:
            result += _randomNum.Next(1, 9);
            break;
    }
}

Or another possibility: Add blocks of LLNN and then truncate the result to the needed length…

for (int i = 0; i <= (length/4); i++)
{
    result += alphabets.ElementAt(_random.Next(23));
    result += alphabets.ElementAt(_random.Next(23));
    result += _randomNum.Next(1, 9); 
    result += _randomNum.Next(1, 9); 
}
result = result.Substring(0,length);

If you want to improve these lines, you can use a StringBuilder

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading