如何在不使用Math.Random的情况下生成随机数?

Joh*_*ith 9 java random

我的项目需要我创建一个使用JOptionPane的基本猜数游戏,并且不使用Math.Random来创建随机值.你会怎么做呢?我已经完成了除随机数发生器之外的所有事情.谢谢!

Fra*_*ank 13

这里是Simple随机生成器的代码:

public class SimpleRandom {
/**
 * Test code
 */
public static void main(String[] args) {
    SimpleRandom rand = new SimpleRandom(10);
    for (int i = 0; i < 25; i++) {
        System.out.println(rand.nextInt());
    }

}

private int max;
private int last;

// constructor that takes the max int
public SimpleRandom(int max){
    this.max = max;
    last = (int) (System.currentTimeMillis() % max);
}

// Note that the result can not be bigger then 32749
public int nextInt(){
    last = (last * 32719 + 3) % 32749;
    return last % max;
}
}
Run Code Online (Sandbox Code Playgroud)

上面的代码是"线性同余生成器(LCG)",你可以在这里找到它的工作原理的一个很好的描述.

Disclamer:

上面的代码仅用于研究,而不是替代库存Random或SecureRandom.


小智 5

在 JavaScript 中使用 Middle-square 方法。

var _seed = 1234;
function middleSquare(seed){
    _seed = (seed)?seed:_seed;
    var sq = (_seed * _seed) + '';
    _seed = parseInt(sq.substring(0,4));
    return parseFloat('0.' + _seed);
}
Run Code Online (Sandbox Code Playgroud)