C # explain how to generate random and non-repeated number instances

Source: Internet
Author: User

Today, a c # random number generation solution is required.
The following are ideas:
First, create a list ArrayList list, set its length to 20, assign a value to it, from 1 to 20.
Then a Random number is generated, which is Random r = new Random (). Every time a random number is generated, the elements in a list are removed.
In this way, there will be no duplicates. Here I changed ArrayList to List, and the following is my code:
Public List <int> GenerateNumber ()
{
Random random = new Random ();
List <int> number = new List <int> (10 );
List <int> result = new List <int> (4 );
For (int I = 0; I <10; I)
{
Number. Add (I );
}
For (int I = 0; I <4; I)
{
Int tempNum = random. Next (0, number. Count );
Result. Add (number [tempNum]);
Number. RemoveAt (tempNum );
}
Return result;
}
The core idea of this practice is to remove the elements in a list every time a random number is generated.

Public static void Main (string [] args)
{
GuessGame guessGame = new GuessGame ();
For (int I = 0; I <guessGame. GenerateNumber (). Count; I)
{
Console. WriteLine (guessGame. GenerateNumber () [I]);
}
}

Related Article

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.