关于生成Java不重复的随机数:
- import java.util.*;
- public class Test...{
- public static void main(String[] args)...{
- //生成 [0-n) 个不重复的随机数
- / st 用来保存这些随机数
- ArrayList list = new ArrayList();
- int n = 10;
- Random rand = new Random();
- boolean[] bool = new boolean[n];
- int num =0;
- for (int i = 0; i<n; i++)...{
- do...{
- //如果产生的数相同继续循环
- num = rand.nextInt(n);
- }while(bool[num]);
- bool[num] =true;
- list.add(num);
- }
- System.out.println (list);
- }
- public class Test
- {
- public static void main(String[] args)
- {
- int[] arr = new int[10];
- for (int i = 0; i < 10; i++)
- {
- arr[i] = (int) (Math.random() * 40) + 1;
- for (int j = 0; j < i; j++)
- {
- if (arr[j] == arr[i])
- {
- i--;
- break;
- }
- }
- }
- for (int i = 0; i < 10; i++)
- System.out.print(arr[i] + " ");
- }
- }
- b.
- Java code
- import java.util.*;
- public class Test
- {
- public static void main(String[] args)
- {
- int n=40;
- int[] num = new int[n];
- for(int i=0;i <num.length;i++)
- num[i] = i+1;
- int[] arr = new int[10];
- for(int i=0;i <arr.length;i++)
- {
- int r =(int)(Math.random()*n);
- arr[i]=num[r];
- num[r]=num[n-1];
- n--;
- }
- for(int i=0;i <arr.length;i++)
- System.out.print(arr[i]+" ");
- }
- }
- c.
- Java code
- import java.util.*;
- public class Test
- {
- public static void main(String[] args)
- {
- LinkedList <Integer> myList= new LinkedList <Integer> ();
- int n=40;
- for(int i=0;i <n;i++)
- myList.add(i+1);
- int[] arr = new int[10];
- for(int i=0;i <arr.length;i++)
- {
- arr[i]=myList.remove((int)(Math.random()*n));
- n--;
- }
- for(int i=0;i <arr.length;i++)
- {
- System.out.print(arr[i]+" ");
- }
- }
- }
- d.
- Java code
- import java.util.*;
- public class Test
- {
- public static void main(String[] args)
- {
- Set <Integer> mySet = new LinkedHashSet <Integer> ();
- while(mySet.size() <10)
- {
- mySet.add((int)(Math.random()*40+1));
- }
- for(Integer i:mySet)
- {
- System.out.print(i+" ");
- }
- }
- }
方法一:
在一个待选数组中随机产生一个数,然后把他放到待选数组的最后,然后从length-1里随机产生下一个随机数,如此类推
- public static int[] randoms()
- {
- Random r = new Random();
- int temp1,temp2;
- 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 len = send.length;
- int returnValue[] = new int[22];
- for(int i=0;i<22;i++)
- {
- temp1 = Math.abs(r.nextInt())% len;
- returnValue[i] = send[temp1];
- temp2 = send[temp1];
- send[temp1] = send[len-1];
- send[len-1] = temp2;
- len--;
- }
- return returnValue;
- }
- }
方法二:
还是一个固定的无重复的数组,然后把这个数组随机调换位置,多次之后这个数组就是一个无重复的随机数组了。
- 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;
- }
【编辑推荐】