|
|
package com.util;
|
|
|
|
|
|
import java.util.Collections;
|
|
|
import java.util.List;
|
|
|
import java.util.Random;
|
|
|
|
|
|
//各种随机数生成
|
|
|
public class RandomUtils {
|
|
|
private static final Random random = new Random();
|
|
|
|
|
|
|
|
|
//生成[min, max]范围内的随机整数(包含边界)
|
|
|
public static int nextInt(int min, int max) {
|
|
|
if (min > max) {
|
|
|
throw new IllegalArgumentException("min不能大于max");
|
|
|
}
|
|
|
return min + random.nextInt(max - min + 1);
|
|
|
}
|
|
|
|
|
|
|
|
|
//从数组中随机选择一个元素(模板类)
|
|
|
public static <T> T randomChoice(T[] array) {
|
|
|
if (array == null || array.length == 0) {
|
|
|
throw new IllegalArgumentException("数组不能为空");
|
|
|
}
|
|
|
return array[random.nextInt(array.length)];
|
|
|
}
|
|
|
|
|
|
|
|
|
//从列表中随机选择一个元素
|
|
|
public static <T> T randomChoice(List<T> list) {
|
|
|
if (list == null || list.isEmpty()) {
|
|
|
throw new IllegalArgumentException("列表不能为空");
|
|
|
}
|
|
|
return list.get(random.nextInt(list.size()));
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 打乱列表顺序
|
|
|
* @param list 要打乱的列表
|
|
|
*/
|
|
|
public static <T> void shuffle(List<T> list) {
|
|
|
Collections.shuffle(list, random);
|
|
|
}
|
|
|
|
|
|
|
|
|
//生成指定范围内的随机双精度浮点数
|
|
|
public static double nextDouble(double min, double max) {
|
|
|
if (min > max) {
|
|
|
throw new IllegalArgumentException("min不能大于max");
|
|
|
}
|
|
|
return min + (max - min) * random.nextDouble();
|
|
|
}
|
|
|
|
|
|
|
|
|
//生成随机布尔值
|
|
|
public static boolean nextBoolean() {
|
|
|
return random.nextBoolean();
|
|
|
}
|
|
|
|
|
|
//按概率返回true(题目生成概率)
|
|
|
//示例:probability(0.7) 有70%概率返回true
|
|
|
public static boolean probability(double probability) {
|
|
|
if (probability < 0.0 || probability > 1.0) {
|
|
|
throw new IllegalArgumentException("概率必须在0.0-1.0之间");
|
|
|
}
|
|
|
return random.nextDouble() < probability;
|
|
|
}
|
|
|
} |