第一种方法,在一个待选数组中随机产生一个数,然后把他放到待选数组的最后,然后从length-1里随机产生下一个随机数,如此类推
public static int[] randoms() int temp1,temp2; |
方法二:还是一个选固定的无重复的数组,,然后把这个数组随机调换位置,多次之后这个数组就是一个无重复的随机数组了。
public static int[] random2() { int send[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21}; int temp1,temp2,temp3; Random r = new Random(); for(int i=0;i<send.length;i++) //随机交换send.length次 { temp1 = Math.abs(r.nextInt())%(send.length-1); //随机产生一个位置 temp2 = Math.abs(r.nextInt())%(send.length-1); //随机产生另一个位置 if(temp1 != temp2) { temp3 = send[temp1]; send[temp1] = send[temp2]; send[temp2] = temp3; } } return send; } |