关于生成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.