生成不重复的随机数数组,算法优化
private void Form1_Load(object sender, EventArgs e)
{
string result = "";
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
List<int> list = new List<int>();
Random random = new Random();
while (list.Count < 100)
{
int t = random.Next(0, 100);
if (!list.Contains(t))
{
list.Add(t);
}
}
watch.Stop();
result += "A:" + watch.ElapsedTicks.ToString();
watch.Restart();
int[] arr = new int[100];
int[] buf = new int[100];
for (int i = 0; i < 100; i++)
{
buf[i] = i;
}
Random ran = new Random();
int bufLength = buf.Length;
for (int i = 0; i < 100; i++)
{
int t = ran.Next(0, bufLength);
arr[i] = buf[t];
buf[t] = buf[bufLength - 1];
bufLength--;
}
watch.Stop();
result += " B:" + watch.ElapsedTicks.ToString();
MessageBox.Show(result);
this.Close();
}
{
string result = "";
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
List<int> list = new List<int>();
Random random = new Random();
while (list.Count < 100)
{
int t = random.Next(0, 100);
if (!list.Contains(t))
{
list.Add(t);
}
}
watch.Stop();
result += "A:" + watch.ElapsedTicks.ToString();
watch.Restart();
int[] arr = new int[100];
int[] buf = new int[100];
for (int i = 0; i < 100; i++)
{
buf[i] = i;
}
Random ran = new Random();
int bufLength = buf.Length;
for (int i = 0; i < 100; i++)
{
int t = ran.Next(0, bufLength);
arr[i] = buf[t];
buf[t] = buf[bufLength - 1];
bufLength--;
}
watch.Stop();
result += " B:" + watch.ElapsedTicks.ToString();
MessageBox.Show(result);
this.Close();
}