我的项目需要我创建一个使用JOptionPane的基本猜数游戏,并且不使用Math.Random来创建随机值。你会怎么做呢?我已经完成了除随机数发生器之外的所有事情。谢谢!
这里是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;
}
}
上面的代码是“线性同余发生器(LCG)”,你可以找到一个很好的描述how it works here.
免责声明:
上面的代码仅用于研究,而不是替代库存Random或SecureRandom。
在JavaScript中使用中间方法。
var _seed = 1234;
function middleSquare(seed){
_seed = (seed)?seed:_seed;
var sq = (_seed * _seed) + '';
_seed = parseInt(sq.substring(0,4));
return parseFloat('0.' + _seed);
}
如果您不喜欢Math.Random,您可以制作自己的Random对象。
进口:
import java.util.Random;
码:
Random rand = new Random();
int value = rand.nextInt();
如果你需要其他类型而不是int,Random将提供boolean,double,float,long,byte的方法。
你可以使用java.security.SecureRandom。它具有更好的熵。
另外,here是本书Data Structures and Algorithm Analysis in Java的代码。它使用与java.util.Random相同的算法。