C # generate 100 random number algorithms, from 1 ~ In 1000, 100 random numbers are generated without duplicates, and hashtable is used. In this way, the number of duplicates is reduced. This is also a frequently asked question during interviews.
The Code is as follows:
Int32 COUNT = 0;
Dictionary <int32, ilist <int32> Results = new dictionary <int, ilist <int> ();
While (count & lt; 100)
{
While (true)
{
Int32 Rand = new random (). Next (1, 1000 );
Int32 mod = Rand % 10;
If (results. Keys. Contains (MOD ))
{
If (! Results [mod]. Contains (RAND ))
{
Results [mod]. Add (RAND );
Count ++;
Break;
}
}
Else
{
Ilist <int32> lists = new list <int32> ();
Lists. Add (RAND );
Results. Add (mod, lists );
Count ++;
Break;
}
}
}
// Output
Foreach (int32 K in results. Keys)
{
Foreach (int32 V in results [k])
{
Response. Write (V. tostring () + "");
}
}
Response. Write ("<br/>" + count. tostring ());
Response. Flush ();
Response. End ();