題目:一個長度為100的整形數組,向其中随機插入1-100之間不重複的數字?
方法一、
int[] arr = new int[100];//數組100個元素
for (int i = 1; i <= 100; i++)
arr[i - 1] = i;//順序指派1~100
Random rnd = new Random(Environment.TickCount);//産生一個随機數
//使用随機順序重排列數組
Array.Sort(arr, (Comparison)delegate(int x, int y)
{
return rnd.Next();
});
foreach (int i in arr)
{
Response.Write(i.ToString()+"<br>");
}
方法二、
List<int> list = new List<int>();
int count = 0;
Random rd = new Random();
while (count < 100)
int temp = rd.Next(1, 101);
if (!list.Contains(temp))
{
list.Add(temp);
count++;
}
int[] arr = list.ToArray();
foreach (int i in arr)
Console.WriteLine(i);