Java Random

基本使用

Random 类提供了丰富的随机方法,使用Random,先要创建一个Random实例。

Random rnd = new Random();
System.out.println(rnd.nextInt());
System.out.println(rnd.nextInt(100));

nextInt() 产生一个随机的int,可能为正数,也可能为负数,nextInt(100) 产生一个随机int,范围是0~100,包括0不包括100。

public void nextBytes(byte[] bytes) // 产生随机字节, 字节个数就是bytes的长度
  
public long nextLong() // 随机生成一个long

public float nextFloat() // 随机浮点数,从0到1,包括0不包括1
  
public double nextDouble() // 随机浮点数,从0到1,包括0不包括1

除了默认构造方法,Random 类还有一个构造方法,可以接受一个 long 类型的种子参数。

种子决定了随机产生的序列,种子相同,产生的随机数序列就是相同的。

Random rnd = new Random(20160824);
for(int i=0; i<5; i++){
  System.out.print(rnd.nextInt(100)+" ");
}

基本原理

Random 产生的随机数不是真正的随机数,它产生的随机数一般称为伪随机数,计算机程序中的随机数一般都是伪随机数。

伪随机数基于种子数,每需要一个随机数,都是对当前种子进行一些数学运算,得到一个数,基于这个数得到需要的随机数和新的种子。

数学运算是固定的,所以种子确定后,产生的随机数序列就是确定的,确定的数字序列当然不是真正的随机数。

Random的默认构造方法中没有传递种子,它会自动生成一个种子,这个种子数是一个真正的随机数。

private static final AtomicLong seedUniquifier = new AtomicLong(8682522807148012L);

public Random() {
  this(seedUniquifier() ^ System.nanoTime());
}

private static long seedUniquifier() {
  for(; ; ) {
    long current = seedUniquifier.get();
    long next = current * 181783497276652981L;
    if(seedUniquifier.compareAndSet(current, next))
      return next;
  }
}

种子是 seedUniquifier() 与 System.nanoTime() 按位异或的结果,System.nanoTime() 返回一个更高精度(纳秒)的当前时间。

使用循环和 compareAndSet 是为了确保在多线程的环境下不会有两次调用返回相同的值,保证随机性。

随机密码

在给用户生成账号时,经常需要给用户生成一个默认随机密码,然后通过邮件或短信发给用户,作为初次登录使用。

private static int nextIndex(char[] chars, Random rnd){
  int index = rnd.nextInt(chars.length);
  while(chars[index]! =0){
    index = rnd.nextInt(chars.length);
  }
  return index;
}

private static char nextSpecialChar(Random rnd){
  return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length()));
}

private static char nextUpperlLetter(Random rnd){
  return (char)('A'+rnd.nextInt(26));
}

private static char nextLowerLetter(Random rnd){
  return (char)('a'+rnd.nextInt(26));
}

private static char nextNumLetter(Random rnd){
  return (char)('0'+rnd.nextInt(10));
}

public static String randomPassword(){
  char[] chars = new char[8];
  Random rnd = new Random();
  chars[nextIndex(chars, rnd)] = nextSpecialChar(rnd);
  chars[nextIndex(chars, rnd)] = nextUpperlLetter(rnd);
  chars[nextIndex(chars, rnd)] = nextLowerLetter(rnd);
  chars[nextIndex(chars, rnd)] = nextNumLetter(rnd);
  for(int i=0; i<8; i++){
    if(chars[i]==0){
      chars[i] = nextChar(rnd);
    }
  }
  return new String(chars);
}

洗牌

一种常见的随机场景是洗牌,就是将一个数组或序列随机重新排列。

private static void swap(int[] arr, int i, int j){
  int tmp = arr[i];
  arr[i] = arr[j];
  arr[j] = tmp;
}

public static void shuffle(int[] arr){
  Random rnd = new Random();
  for(int i=arr.length; i>1; i--) {
    swap(arr, i-1, rnd.nextInt(i));
  }
}

带权重的随机选择

实际场景中,经常要从多个选项中随机选择一个,不过,不同选项经常有不同的权重。比如,给用户随机奖励,三种面额:1元、5元和10元,权重分别为70、20和10。

实现的基本思路是,使用概率中的累计概率分布。以上面的例子来说,计算每个选项的累计概率值,首先计算总的权重,这里正好是100,每个选项的概率是70%、20%和10%,累计概率则分别是70%、90%和100%。

有了累计概率,则随机选择的过程是:使用nextDouble()生成一个0~1的随机数,然后使用二分查找,看其落入哪个区间,如果小于等于70%则选择第一个选项,70%和90%之间选第二个,90%以上选第三个。

class Pair {
  Object item;
  int weight;
  public Pair(Object item, int weight){
    this.item = item;
    this.weight = weight;
  }
  public Object getItem() {
    return item;
  }
  public int getWeight() {
    return weight;
  }
}
public class WeightRandom {
  private Pair[] options;
  private double[] cumulativeProbabilities;
  private Random rnd;
  public WeightRandom(Pair[] options){
    this.options = options;
    this.rnd = new Random();
    prepare();
  }
  private void prepare(){
    int weights = 0;
    for(Pair pair : options){
      weights += pair.getWeight();
    }
    cumulativeProbabilities = new double[options.length];
    int sum = 0;
    for(int i = 0; i<options.length; i++) {
      sum += options[i].getWeight();
      cumulativeProbabilities[i] = sum / (double)weights;
    }
  }
  public Object nextItem(){
    double randomValue = rnd.nextDouble();
    int index = Arrays.binarySearch(cumulativeProbabilities, randomValue);
    if(index < 0) {
      index = -index-1;
    }
    return options[index].getItem();
  }
}

抢红包

维护一个剩余总金额和总数量,分配时,如果数量等于1,直接返回总金额,如果大于1,则计算平均值,并设定随机最大值为平均值的两倍,然后取一个随机值,如果随机值小于0.01,则为0.01,这个随机值就是下一个的红包金额。

public class RandomRedPacket {
  private int leftMoney;
  private int leftNum;
  private Random rnd;
  public RandomRedPacket(int total, int num){
    this.leftMoney = total;
    this.leftNum = num;
    this.rnd = new Random();
  }
  public synchronized int nextMoney(){
    if(this.leftNum<=0){
      throw new IllegalStateException("抢光了");
    }
    if(this.leftNum==1){
      return this.leftMoney;
    }
    double max = this.leftMoney/this.leftNum*2d;
    int money = (int)(rnd.nextDouble()*max);
    money = Math.max(1, money);
    this.leftMoney -= money;
    this.leftNum --;
    return money;
  }
}

购车摇号

1)每期摇号前,将每个符合摇号资格的人,分配一个从0到总数的编号,这个编号是公开的,比如总人数为2 304 567,则编号为0~2 304 566。

2)摇号第一步是生成一个随机种子数,这个随机种子数在摇号当天通过一定流程生成,整个过程由公证员公证,就是生成一个真正的随机数。

3)种子数生成后,然后就是循环调用类似 Random.nextInt(int n) 方法,生成中签的编号。

编号是事先确定的,种子数是当场公证随机生成的,是公开的,随机算法是公开透明的,任何人都可以根据公开的种子数和编号验证中签的编号。

双色球

int[] toRedBalls = new int[33];
for(int i = 0, len = toRedBalls.length; i < len; i++) {
    toRedBalls[i] = i+1;
}

Random random = new Random();

// 从 1 ~ 33 随机生成 6 个红球
int[] sysRedBalls = new int[6];
for(int i = 0; i < sysRedBalls.length; i++) {
    int index = random.nextInt(toRedBalls.length - i); // [0, toRedBalls.length - 1 - i]
    sysRedBalls[i] = toRedBalls[index];
    toRedBalls[index] = toRedBalls[toRedBalls.length - 1 - i];
    toRedBalls[toRedBalls.length - 1 - i] = sysRedBalls[i];
}
// 随机生成一个蓝球
int sysBlueBall = random.nextInt(16) + 1;

int[] userRedBalls = new int[6];
int userBlueBall = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("双色球开始,请问机选还是 手选?1:机选;2:手选");
int isAuto = 0;
if(scanner.hasNextInt()){
    isAuto = scanner.nextInt();
}
switch (isAuto) {
    case 1:
        for(int i = 0; i < userRedBalls.length; i++) {
            int index = random.nextInt(toRedBalls.length - i); // [0, toRedBalls.length - 1 - i]
            userRedBalls[i] = toRedBalls[index];
            toRedBalls[index] = toRedBalls[toRedBalls.length - 1 - i];
            toRedBalls[toRedBalls.length - 1 - i] = userRedBalls[i];
        }
        userBlueBall = random.nextInt(16) + 1;
        break;
    case 2:
        System.out.println("请选择6个红球号码(1~33)");
        for(int i = 0; i < userRedBalls.length; i++) {
            if(scanner.hasNextInt()){
                userRedBalls[i] = scanner.nextInt();
            } else {
                System.out.println(scanner.next());
            }
        }
        System.out.println("请选择1个篮球号码(1~16)");
        if(scanner.hasNextInt()){
            userBlueBall = scanner.nextInt();
        }
        break;
}

// 统计结果
int redCount = 0;
int blueCount = 0;

for(int i = 0, len = userRedBalls.length; i < len; i++) {
    for(int j = 0, sysLen = sysRedBalls.length; j < sysLen - redCount; j++) {
        if(userRedBalls[i] == sysRedBalls[j]) {
            redCount++;
            sysRedBalls[j] = sysRedBalls[sysLen - 1 - redCount];
            sysRedBalls[sysLen - 1 - redCount] = userRedBalls[i];
            break;
        }
    }
}

if(userBlueBall == sysBlueBall) {
    blueCount = 1;
}

if(redCount <= 3 && blueCount == 0) {
    System.out.println("革命尚未成功");
} else if(redCount < 3 && blueCount == 1) {
    System.out.println("六等奖,5块钱");
} else if((redCount == 3 && blueCount == 1)
          || (redCount == 4 && blueCount == 0)) {
    System.out.println("五等奖,10块钱");
} else if((redCount == 4 && blueCount == 1)
          || (redCount == 5 && blueCount == 0)) {
    System.out.println("四等奖,200块钱");
} else if(redCount == 5 && blueCount == 1) {
    System.out.println("三等奖,3000块钱");
} else if(redCount == 6 && blueCount == 0) {
    System.out.println("二等奖,150w");
} else if(redCount == 6 && blueCount == 1) {
    System.out.println("一等奖,500w");
}

System.out.println("本期红球号码:" + Arrays.toString(sysRedBalls));
System.out.println("本期蓝球号码:" + sysBlueBall);
System.out.println("你选择的红球号码:" + Arrays.toString(userRedBalls));
System.out.println("你选择的蓝球号码:" + userBlueBall);
System.out.println("红球中了:" + redCount);
System.out.println("蓝球中了:" + blueCount);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容