Two ways to generate a random number that is not repeated

Source: Internet
Author: User
Keywords Compare pass implement follow
Tags code example random static string using

Let me take a example of three ways to generate a random number of duplicates by using the 10 random numbers that generate 1-10:
1. Through the while loop to achieve
This method is easy to think of, but inefficient, with the instance code as follows: the constant generation of random numbers through a while loop until a repeat is generated.

static void Main (string] args)
{
int] result = new INT[10];
int tmp =-1;
Random Random = new Random ();
BOOL repeat = FALSE;
for (int i = 0; i < i++)
{
repeat = true;
while (repeat)
{
repeat = false;

TMP = random. Next (1, 11);
for (int j = 0; J < i; J + +)
{
if (TMP = = Result[j])
{
repeat = true;
Break;
}
}
}
Result[i] = tmp;

}

for (int i = 0; i < i++)
Console.WriteLine (Result[i]. ToString ());
}

2. Implement for Loop
Method 1 uses many loops nesting, the efficiency is very low, therefore I apply certain technique to reduce the cyclic nesting, achieves enhances the program efficiency the goal. The main idea is that if you detect repetition, the loop variable is reduced by 1, so that you can redo the loop again, and then regenerate a random number until a random number of duplicates is generated, the instance code is as follows:

static void Main (string] args)
{
int] result = new INT[10];
int tmp =-1;
Random Random = new Random ();
BOOL repeat = FALSE;
for (int i = 0; i < i++)
{
repeat = false;

TMP = random. Next (1, 11);
for (int j = 0; J < i; J + +)
{
if (TMP = = Result[j])
{
repeat = true;
Break;
}
}
if (!repeat)
{
Result[i] = tmp;
}
Else
{
i = i-1;//loop variable-1
}


}

for (int i = 0; i < i++)
Console.WriteLine (Result[i]. ToString ());
}

This method reduces a layer of cycle nesting, the efficiency of a certain improvement!

Summary:

Method 1 efficiency is relatively low, generally not recommended to use!
Method 2 is more general and more efficient than Method 1.
Please give us a lot of advice Ah!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.