这道题目很值得思考,以下分别用三种方式搞定,第三种方式拒绝使用contains方法。
方法一:
int[] arr = new int[100];
// while (true)
// {
// Random rand = new Random();
// for (int j = 0; j < 100; j++)
// {
// int m = rand.Next(1, 200);
// if (!arr.Contains(m))
// {
// arr[j] = m;
// }
// else
// j--;
// }
// break;
方法一变形:
int[] arr = new int[100];
Random rnd = new Random ();
for (int i = 0; i < 100; )
{
int j= rnd.Next(1, 101);
if (arr.Contains(j) == false )
{
arr[i] = j;
i++;
}
}
for (int k = 0; k < 100; k++)
{
Console.Write(arr[k] + " ");
}
方法二:
//int[] arr = new int[100];
//ArrayList list = new ArrayList();
//Random rand = new Random();
//while (list.Count < 100)
//{
// int num = rand.Next(1, 105);
// if (!list.Contains(num))
// list.Add(num);
//}
//for (int i = 0; i < 100; i++)
// arr[i] = (int)list[i];
方法三:
int[] arr1 = new int[100];
int[] arr2 = new int[100];
for (int i = 0; i < 100; i++)
arr1[i] = i;
Random rand=new Random();
int end=100-1;
for(int i=0;i<total;i++)
{
int num= rand.Next(0, end+1);
arr2[i] = arr1[num];
arr2[num] = arr2[end];
end--;
}