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]);
}
}