简体   繁体   English

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

[英]How can I generate a random number without use of Math.Random?

My project entails that I create a basic number guessing game that uses the JOptionPane and does not use Math.Random to create the random value. 我的项目需要我创建一个使用JOptionPane的基本猜数游戏,并且不使用Math.Random来创建随机值。 How would you go about doing this? 你会怎么做呢? I've completed everything except the random number generator. 我已经完成了除随机数发生器之外的所有事情。 Thanks! 谢谢!

Here the code for a Simple random generator: 这里是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;
}
}

The code above is a "Linear congruential generator (LCG)", you can find a good description of how it works here. 上面的代码是“线性同余生成器(LCG)”,你可以在这里找到它的工作原理的一个很好的描述

Disclamer: Disclamer:

The code above is designed to be used for research only, and not as a replacement to the stock Random or SecureRandom. 上面的代码仅用于研究,而不是替代库存Random或SecureRandom。

In JavaScript using the Middle-square method. 在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);
}

If you don't like the Math.Random you can make your own Random object. 如果您不喜欢Math.Random,您可以创建自己的Random对象。

import: 进口:

import java.util.Random;

code: 码:

Random rand = new Random();
int value = rand.nextInt();

If you need other types instead of int, Random will provide methods for boolean, double, float, long, byte. 如果你需要其他类型而不是int,Random将提供boolean,double,float,long,byte的方法。

You could use java.security.SecureRandom . 您可以使用java.security.SecureRandom It has better entropy. 它具有更好的熵。

Also, here is code from the book Data Structures and Algorithm Analysis in Java . 此外, 这里Java中的数据结构和算法分析一书中的代码。 It uses the same algorithm as java.util.Random. 它使用与java.util.Random相同的算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM