我需要一个函数来生成随机整数.(long现在假设Java 类型,但这将扩展到BigInteger或BitSet稍后.)
棘手的部分是有一个参数P,它指定结果中任何位的(独立)概率为1.
如果P = 0.5,那么我们可以使用标准随机数发生器.P的一些其他值也易于实现.这是一个不完整的例子:
Random random = new Random();
// ...
long nextLong(float p) {
if (p == 0.0f) return 0L;
else if (p == 1.0f) return -1L;
else if (p == 0.5f) return random.nextLong();
else if (p == 0.25f) return nextLong(0.5f) & nextLong(0.5f);
else if (p == 0.75f) return nextLong(0.5f) | nextLong(0.5f);
else if (p == 0.375f) return nextLong(0.5f) & nextLong(0.75f); // etc
else {
// What goes here??
String message …Run Code Online (Sandbox Code Playgroud)