Java如何生成长度为n,范围为[l, r]的随机整数数组

package com.oceanstar;

import java.util.Arrays;
import java.util.Random;

public class Main {

    // 生成一个长度为n,范围在[rangeL, rangeR]内的随机数组
    public static int[] generateRandomArray(int length, int rangeL, int rangeR){
        if (length <0  || rangeR <= rangeL) {
            return null;
        };

        return  new Random().ints(rangeL, rangeR).limit(length).toArray();
    }

    // 生成一个长度为n,范围在[rangeL, rangeR]内的不重复的随机数组
    public static int[] generateRandomDistinctArray(int length, int rangeL, int rangeR){
        if (length <0  || rangeR <= rangeL || (rangeR - rangeL + 1) < length) {
            return null;
        };

        return  new Random().ints(rangeL, rangeR).distinct().limit(length).toArray();
    }

/*    public  static  void printArray(int [] array){
        for (int i = 0; i < array.length; i++){
            System.out.print(array[i] + "\t");
        }
    }*/

    public static void main(String[] args) {
       int [] arr =  generateRandomArray(10, 0, 5);
       System.out.println(Arrays.toString(arr));
    }
}

你可能感兴趣的:(算法与数据结构)