產生一個不重複的隨機數組(元素各不相同的隨機數組)的算法

產生一個 由0到99之間的數組成,元素各不相同的無序的一個長度爲100的數組。

 

其實換句話說,就是把一個 由0到100之間的一個 連續的數組給打散。

 

由三種方式。

 

一:使用List 和隨機數

//  long s1 = System.currentTimeMillis();

 //  List ar = new ArrayList();  
//   for (int i = 0; i < 100000; i++) {
//    ar.add(i);
//   }
 
//   int [] toArray = new int[100000];
//   
//   for(int j = 100000; j >0; j--){
//     double d  = (Math.random()*j);
//     int index = (int)d;
//     toArray[j-1]= (int)ar.get(index);
//     ar.remove(ar.get(index));
//   }
 
//   long s2 = System.currentTimeMillis();

 //   System.out.println("S2-S1用時:"+(s2 - s1)); //S2-S1:14881

二.通過對原來數組元素位置的交換,而不是把原來集合中的元素移除,來產生無序數組

   long s1 = System.currentTimeMillis();  

   int [] ar = new int[100];

   for (int i = 0; i < 100; i++) {
       ar[i]=i;
   }
 
   int [] toArray = new int[100];
  
  for(int j = 100; j >0; j--){

     int index  = (int)(Math.random()*j);     

     toArray[j-1]= ar[index];

     int temp  = ar[index];

     ar[index] = ar[j-1];

     ar[j-1] = temp;

   }

   long s2 = System.currentTimeMillis();

   System.out.println("S2-S1:"+(s2 - s1));

三: 給原來數組的每個元素定義一個開關, 通過開關判斷元素是否重複,如果重複 會繼續產生隨機數,知道不重複爲止

  long s1 = System.currentTimeMillis();
 
  //計數器 標記這個方法一共循環多少次 
  int c = 0;
  
   //這是0-99個數
  int[] iqs = new int[100000];
  for (int i = 0; i < 100000; i++) {
   iqs[i] = i;
  }
 
  //這是隨機數組
  int[] sb = new int[100000];
  //設置開關
  boolean[] b = new boolean[100000];
  //賦值
  for (int i = 0; i < 100000; i++) { // 遍歷iqs數組
   int index;
   do {
    c++;
    index = (int) (Math.random() * iqs.length); // iqs數組的隨機下標
   } while (b[index] == true); // b[index]爲true代碼生成過對應字符,則重新生成下標
       sb[i] = iqs[index]; // 取出iqs中的元素賦值給sb中的每一個元素
       b[index] = true; // true代表已生成過
  }
  
   System.out.println(c);
   long s2 = System.currentTimeMillis();
   System.out.println(s2 - s1);
  return sb;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章