0-99的不重复乱序排列数组

论坛地址:http://topic.csdn.net/u/20081220/10/45dbe268-63b7-43c5-b477-cd9c808a4edf.html?seed=211094149

我的代码:

  1. import java.util.*;
  2. /**
  3.  * 生成一个100个数字以内无序数组,不重复
  4.  * @author 李晗
  5.  *
  6.  */
  7. public class lihan {
  8.   public static final int HOWMANY=100;
  9.   public static int fill(int[]kaka){
  10.     ArrayList al=new ArrayList();
  11.     for(int i=1;i<=HOWMANY;i++){
  12.       al.add(new Integer(i));
  13.     }
  14.     
  15.     //生成无序的数组
  16.     for(int i=1;i<=HOWMANY-1;i++){
  17.       int pos=(int)(Math.random()*al.size());
  18.       kaka[i]=((Integer)al.get(pos)).intValue();
  19.       al.remove(pos);
  20.     }
  21.     kaka[HOWMANY]=-1;
  22.     return ((Integer)al.get(0)).intValue();
  23.   }
  24.   //打印出数组
  25.   public static void printArray(int[]a){
  26.     for(int i=1;i<a.length;i++){
  27.       System.out.print(a[i]+" ");
  28.     }
  29.     System.out.println();
  30.   }
  31.   public static void main(String[]args){
  32.     int []h=new int[HOWMANY+1];
  33.     fill(h);
  34.     printArray(h);
  35.   }
  36. }

 

后来发现别人的不错,思路拿来,顺便改一下:

  1. import java.util.*;  
  2. public class lihan {  
  3.       
  4.     public static void main(String[] args) {  
  5.         int[] seed=new int[100];
  6.         for(int k=0;k<100;k++)
  7.         {
  8.             seed[k]=k;
  9.         }
  10.         int [] ranArr = new int [100];  
  11.         Random ran = new Random();  
  12.         for(int i = 0 ; i <seed.length ; i++){  
  13.             int j = ran.nextInt(seed.length-i);  
  14.             ranArr [i] = seed [j];  
  15.             seed [j] = seed [seed.length-1-i];  
  16.             System.out.print (ranArr[i]+" ");  
  17.         }  
  18.     }  
  19. }  

打印结果:53 67 44 12 61 34 5 16 85 74 4 92 54 58 55 88 22 72 28 77 8 56 38 91 75 82 33 73 31 7 98 62 84 37 17 6 87 25 94 18 19 71 30 36 41 46 11 50 1 90 42 83 48 63 39 40 43 51 96 95 69 99 15 97 20 26 47 2 93 79 52 80 3 59 65 70 13 57 9 32 81 0 14 76 49 35 86 10 21 78 24 66 60 64 89 29 68 27 45 23

 

第二次执行:19 57 87 40 1 21 14 10 15 5 90 9 65 6 84 41 12 53 59 33 89 34 25 16 72 88 85 36 79 97 58 69 77 2 95 39 55 8 96 28 11 37 64 43 45 4 92 29 91 68 73 93 32 20 23 30 74 7 35 49 48 67 18 83 78 3 26 17 22 70 76 81 31 62 51 54 71 98 82 24 60 47 0 80 63 56 61 38 50 86 94 13 27 66 75 44 42 46 99 52

 

你可能感兴趣的:(0-99的不重复乱序排列数组)