1. //获取count个不大于maxNumber的整数,所有整数不重复。当然,count必须小于等于maxNumber  
  2.   
  3. static List<int> GetRandomArray(int maxNumber,int count)  
  4. {  
  5.      List<int> list = new List<int>();//保存取出的随机数  
  6.     int[] array=new int[maxNumber];//定义初始数组  
  7.     for (int i = 0; i < maxNumber; i++)//给数组元素赋值  
  8.          array[i] = i + 1;  
  9.      Random rnd = new Random();  
  10.     for (int j = 0; j < count; j++)  
  11.      {  
  12.         int index = rnd.Next(j,maxNumber);//生成一个随机数,作为数组下标  
  13.         int temp = array[index];//从数组中取出index为下标的数  
  14.          list.Add(temp);//将取出的数添加到list中  
  15.          array[index] = array[j];//将下标为j的数交换到index位置  
  16.          array[j] = temp;//将取出的数交换到j的位置  
  17.      }  
  18.     return list;  
  19. }  

相关文章:

  • 2021-08-16
  • 2021-10-19
  • 2022-12-23
  • 2021-10-19
  • 2021-11-26
  • 2021-09-02
猜你喜欢
  • 2022-12-23
  • 2021-10-19
  • 2022-01-11
  • 2021-10-29
相关资源
相似解决方案