ksg
ksg

Reputation: 4067

Unique 4 digit random number in C#

I want to generate an unique 4 digit random number. This is the below code what I have tried:

Code for generating random number

//Generate RandomNo
public int GenerateRandomNo()
{
    int _min = 0000;
    int _max = 9999;
    Random _rdm = new Random();
    return _rdm.Next(_min, _max);
}

The problem is I have received a random no with value 241 which is not a 4 digit number. Is there any problems with the code?

Upvotes: 29

Views: 83533

Answers (13)

Moon
Moon

Reputation: 35265

private Random _random = new Random();

public string GenerateRandomNo()
{
    return _random.Next(0, 9999).ToString("D4");
}

Upvotes: 37

b_scored
b_scored

Reputation: 21

Here is Method to generate any digits number. The loop inside will regenerate the number if it contains duplicate digits, so the random number will consist from unique digits only.

using System.Linq;

public static int GenerateRandomNum()
    {
        // Number of digits for random number to generate
        int randomDigits = 4;
        
        int _max = (int)Math.Pow(10, randomDigits);
        Random _rdm = new Random();
        int _out = _rdm.Next(0, _max);

        while (randomDigits != _out.ToString().ToArray().Distinct().Count())
        {
            _out = _rdm.Next(0, _max);
        }
        return _out;
    }

Upvotes: 0

Marco Concas
Marco Concas

Reputation: 1892

Using this you will avoid starting numbers with 00[...] and you can also specify the length.

string RandomNumbers(int Length)
{
    Random Rand = new Random();
    StringBuilder SB = new StringBuilder();
    for (int i = 0; i < Length; i++)
        SB.Append(Rand.Next(0, 9));

    return SB.ToString();
}

RandomNumbers(4) // OUTPUT: 9301, 4936, 0692, etc ...

Upvotes: 0

indofraiser
indofraiser

Reputation: 1024

Expanding on the answer from brij but with 0000 to 9999 rather than 1000 to 9999

string formatting = "0000"; //Will pad out to four digits if under 1000   
int _min = 0;
int _max = 9999;
Random randomNumber = new Random();
var randomNumberString = randomNumber.Next(_min, _max).ToString(formatting);

or if you want to minimalize lines:

Random randomNumber = new Random();
var randomNumberString = randomNumber.Next(0, 9999).ToString("0000");

Upvotes: 0

Belal Abu hammour
Belal Abu hammour

Reputation: 11

int NoDigits = 4;
Random rnd = new Random();
textBox2.Text = rnd.Next((int)Math.Pow(10, (NoDigits - 1)), (int)Math.Pow(10, NoDigits) -1).ToString();

Upvotes: 1

Brij Raj Singh - MSFT
Brij Raj Singh - MSFT

Reputation: 5113

//Generate RandomNo
public int GenerateRandomNo()
{
    int _min = 1000;
    int _max = 9999;
    Random _rdm = new Random();
    return _rdm.Next(_min, _max);
}

you need a 4 digit code, start with 1000

Upvotes: 69

Daumantas Drukteinis
Daumantas Drukteinis

Reputation: 45

I suggest to create new list and check if this list contains any of number

var IdList = new List<int>();
do
{
    billId = random.Next(1, 9000);
} while (IdList.Contains(billId));
IdList.Add(billId);

Upvotes: 1

Saif
Saif

Reputation: 434

Just one line code

int num = new Random().Next(1000, 9999);

Upvotes: 9

Muhammad Awais
Muhammad Awais

Reputation: 4492

Random generator = new Random();
string number = generator.Next(1, 10000).ToString("D4");

Upvotes: 3

Baskar Rao
Baskar Rao

Reputation: 470

You can consider something like this.

int length = 4;
int number = 50;
string asString = number.ToString("D" + length);

The above code gives the result 0050.

Similarly you can try converting to string and verify.

Upvotes: -1

amit dayama
amit dayama

Reputation: 3326

use: int _min = 1000;

or use leading 0 in case if you want 0241

Upvotes: 2

Steve Wellens
Steve Wellens

Reputation: 20620

0 is the same as 0000.

241 is the same as 0241.

You could format the integer to a string with a leading zero.

Upvotes: 6

x0n
x0n

Reputation: 52410

241 is a four digit number, if you use leading zeros: 0241.

Display the returned number with a format string like this:

String.Format("{0:0000}", n);

Upvotes: 9

Related Questions