All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.jiangzeyin.RandomUtil Maven / Gradle / Ivy

There is a newer version: 1.0.13
Show newest version
package cn.jiangzeyin;

import java.util.Random;

/**
 * Created by jiangzeyin on 2017/11/2.
 */
public final class RandomUtil {
    private static final Random random = new Random();
    private static final String base = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";

    private RandomUtil() {
    }

    /**
     * 生成随机字符串
     * 

* 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1 * * @param length 长度 * @return 结果 */ public static String getRandomString(int length) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } /** * 随机生成指定长度的int 类型数字 * * @param length 长度 * @return 结果 */ public static int getRandomCode(int length) { int min = 1; int max = 9; int seep = 1; for (int i = 0; i < length - 1; i++) { min *= 10; seep *= 10; seep++; } if (seep != 1) max *= seep; return getRandom(min, max); } /** * 随机生成指定范围的随机数 * * @param min 最小值 * @param max 最大值 * @return 结果 */ public static int getRandom(int min, int max) { if (max < min) throw new IllegalArgumentException("max < min"); return random.nextInt(max) % (max - min + 1) + min; } /** * 随机获取数组中一个元素 * * @param objects 数组 * @param 泛型 * @return object */ public static T getRandomArray(T[] objects) { if (objects == null || objects.length < 1) throw new IllegalArgumentException("objects is null"); int index = random.nextInt(objects.length); return objects[index]; } /** * 获取权重随机信息 * * @param weights 权重数组 * @return 返回随机结果后的下标 */ public static int getWeightRandom(int[] weights) { int weightSum = 0; for (int item : weights) { weightSum += item; } int n = random.nextInt(weightSum); // n in [0, weightSum) int m = 0; for (int i = 0, len = weights.length; i < len; i++) { int weight = weights[i]; if (m <= n && n < m + weight) { return i; } m += weight; } return 0; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy