简体   繁体   中英

Exclude numbers starting with a certain three digits in C#

I am currently building a C# application that is generating a random 9 digit number each run through. I am looking for a way to exclude numbers starting with "666". How would I go about writing a statement to exclude numbers starting with certain digits.

Here's the code snippet just in case it helps.

Random SSN = new Random();
string temp = "";
int num = SSN.Next(100000000, 999999999);
temp = num.ToString();

Thanks!

Well, you could write:

int num;
do {
   num = SSN.Next(100000000, 999999999);
} while (num >= 666000000 && num < 667000000);

(I originally used a string comparison too, but as we've always got exactly 9 digits, we can make a numeric comparison easily.)

The easy way would be:

Random SSN = new Random();
string temp = "";
do
{
    int num = SSN.Next(100000000, 999999999);
    temp = num.ToString();
} while (temp.StartsWith("666"));

If you're really into efficiency and want to avoid the string comparison and unbounded loop at all costs, you could use:

Random SSN = new Random();
int num = SSN.Next(100000000, 998999999);
if (num >= 666000000)
    num += 1000000;
Random SSN = new Random();
string temp = "";
double d = 0.6; // This will help on of choosing one half

int n1 = SSN.Next(100000000, 666000000);
int n2 = SSN.Next(667000000, 999999999);

int num = SSN.NextDouble() > d ? n1 : n2; 

temp = num.ToString();
Random SSN = new Random();
string temp = "";
do
{
    int num = SSN.Next(100000000, 999999999);
    temp = num.ToString();
} while(num.IndexOf("666") == 0);

This has complexity of O(1).

                string temp = "";
                if (SSN.Next(0,999999999) < 588339221)
                {
                    temp = SSN.Next(100000000, 666000000).ToString();
                }
                else
                {
                    temp = SSN.Next(667000000, 1000000000).ToString();
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM