欢迎访问宙启技术站
智能推送

Java函数如何实现不重复随机数生成?

发布时间:2023-06-16 20:52:07

在Java函数中实现不重复随机数生成有多种方法,以下是其中一些方法的详细解释。

1. 使用Random类生成随机数并放入Set集合中

代码实现:

Random random = new Random();
Set<Integer> set = new HashSet<>();
while (set.size() < n) {
    set.add(random.nextInt(upperBound));
}
int[] result = set.stream().mapToInt(Integer::intValue).toArray();
return result;

以上代码使用Random类生成随机数并放入HashSet集合中,HashSet的特点是不能存储重复的元素,在添加元素时会自动排除重复元素。直到生成的元素数量达到要求,将HashSet转换为数组并返回即可。

2. 使用Collections.shuffle打乱数组顺序

代码实现:

List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
    list.add(i);
}
Collections.shuffle(list);
int[] result = list.stream().mapToInt(Integer::intValue).toArray();
return result;

以上代码首先将所需元素的序号放入一个List集合中,然后调用Collections.shuffle方法打乱元素的顺序,再将List转换为数组返回即可。

3. 使用Stream.generate生成随机无限流,再利用distinct和limit截取固定数量不重复元素

代码实现:

public static int[] getRandomNumbers(int n, int upperBound) {
    Random random = new Random();
    return Stream.generate(() -> random.nextInt(upperBound))
            .distinct()
            .limit(n)
            .mapToInt(Integer::intValue)
            .toArray();
}

以上代码使用Stream.generate生成一个无限流,使用Random类生成随机数,然后使用distinct方法剔除重复元素,使用limit方法截取指定数量元素,并将流转换为数组返回即可。

4. 使用ThreadLocalRandom类生成随机数并放入Set集合中

代码实现:

int[] result = ThreadLocalRandom.current().ints(0, upperBound)
            .distinct()
            .limit(n)
            .toArray();
return result;

以上代码使用ThreadLocalRandom类生成随机数,使用ints生成指定数量元素,使用distinct和limit方法剔除重复元素,并将流转换为数组返回即可。

总结:

以上四种方法实现的原理不同,适用于不同的应用场景,可以根据具体需要选择可行的方法来实现不重复随机数的生成。