Java - Math.random 使用

By sunwc 2023-03-17 Java

原始random區間為包含0.0且不包含1.0 => [0.0,1.0)

我們可以透過公式Math.random*(b-a+1)+a 取得區間[a,b)的一個數字

例子

 public static void main(String[] args) {
        // 原始random區間為包含0.0且不包含1.0
        double random = Math.random();// [0.0,1.0)

        // [10-99] 如何取得10-99之間的數:公式 - (b-a+1)+a
        int result = (int)(Math.random() * (99 - 10) + 1 + 10);
        System.out.println(result);

        // [888-999] 如何取得888-999之間的數:
        result = (int)(Math.random() * (999 - 888 + 1) + 888);
        System.out.println(result);
    }

例子

  • 陣列長度10放入隨機數[10-99]、且不重複
public static void main(String[] args) {
    int[] arr = new int[10];
    arr[0] = (int) (Math.random() * (99 - 10 + 1) + 10);
    
    // 用來判斷隨機數是否重複
    Set set = new HashSet<Integer>();
    set.add(arr[0]);
    
    int max = arr[0];
    int min = arr[0];
    int sum = 0;
    int average = 0;
    for (int i = 1; i < arr.length; i++) {
        // 隨機數都是兩位數
        int random = (int) (Math.random() * (99 - 10 + 1) + 10);
        if (set.contains(random)) {
            i--;
        } else {
            // 未重複
            
            arr[i] = random;
            // 計算總和
            sum += arr[i];
            // 計算最大值
            if (max < arr[i]) {
                max = arr[i];
            }
            // 計算最小值
            if (min > arr[i]) {
                min = arr[i];
            }
            set.add(random);
        }
    }
    
    System.out.println("min="+min+",max="+max+",average="+sum/arr.length);
    System.out.println(Arrays.toString(arr));
}