In order to complete the interview as soon as possible, the first response is to create an array and then generate a random1-100And then compare it with the array. If this number is not in the array, this method is not good, but it can implement the function. ExampleCodeAs follows:
Static VoidMain (String[] ARGs)
{
Int[] Num= New Int[100];
List<Int>Temp= New List<Int>();
RandomRand= New Random();
IntNumber= 0;
For(IntIndex= 0; Index<Num.Length; index++)
{
Do
{
//Generate 1-numbers randomly
Number=Rand.Next (1,100);
}While(Temp.Indexof (number)! = -1);
Num [Index]=Number;
Temp.Add (number );
}
//Show data
Foreach(IntItemInNum)
{
Console.Write (String.Format ("{0} \ t", Item ));
}
Console.Read ();
}
After going home, I wrote code on the machine for testing and found that the above method is not only bad, but also very low in efficiency and does not display data at all.
After thinking:1-100To generate a length100Is it not the array that fills the one hundred number, but the filling position can be randomly generated.Write down the following implementationProgram:
Static VoidMain (String[] ARGs)
{
Int[] Num= New Int[100];
RandomRand= New Random();
IntNumber= 1;
For(IntIndex= 0; Index<= 99; Index++)
{
Num [Index]=Number++;
//Randomly generate array subscript
IntRandindex=Rand.Next (0, Index );
//Replace Data
IntTemp=Num [randindex];
Num [randindex]=Num [Index];
Num [Index]=Temp;
}
Foreach(VaRItemInNum)
{
Console.Write (String.Format ("{0} \ t", Item ));
}
Console.Read ();
}
In this way, it seems that the question requirements are not met, and only the filled data is randomly disrupted. After thinking again, you can first prepare a data set of 1-, randomly obtain the numbers in the set to the array, remove the obtained numbers, and then obtain them randomly.
The implementation procedure is as follows:
Class Program
{
Static VoidMain (String[] ARGs)
{
List<Int>List= New List<Int>();
For(IntNumber= 1; Number<= 100; Number++)
{
List.Add (number );
}
//Randomly retrieve a number in the number of columns. After obtaining the number, remove the number.
Int[] Num= New Int[100];
RandomRand= New Random();
IntListindex= 0;
For(IntIndex= 0; Index<= 99; Index++)
{
Listindex=Rand.Next (0, List.Count );
Num [Index]=List [listindex];
List.Remove (Num [Index]);
}
//Show data
Foreach(IntItemInNum)
{
Console.Write (String.Format ("{0} \ t", Item ));
}
Console.Read ();
}
}
In this way, the implementation efficiency is relatively high, it also meets the requirements of the question, and is made up of random components.
I don't know who is thinking about this question first. Is there a better way to achieve this? Thank you!