开发者

How to generate no from 1 to 1000 randomly without using random class in java?

开发者 https://www.devze.com 2023-02-11 10:16 出处:网络
I want to generate array position 开发者_开发技巧from 1 to 1000 randomly using some mathematical formula and without java.util.Random class in Java. I want to generate same random series at client and

I want to generate array position 开发者_开发技巧from 1 to 1000 randomly using some mathematical formula and without java.util.Random class in Java. I want to generate same random series at client and server side. How can I do this?


If your real requirement is "same random series at client and server" the you can use Random with exactly same initial seed.

And actually java Random uses mathematical formula, and it's not truly random.

Example:

Random client = new Random(12345);
Random server = new Random(12345);

for (int i = 0; i < 100; i++) {
   assert client.nextInt() == server.nextInt();
}


Well, without using the Random class, you could use the current time to generate a random number, then get it back in the 1-1000 range. Something like (crude, but hey...) :

long time = System.currentTimeMillis();
long rand = time % 1000;

EDIT : didn't see the "same on client and server" part... Then the answer of Splix above using the random class with a given initial seed seems indeed like the way to go.


If the client and server are presumably communicating with either other, the simplest way to implement this is just to have the server generate a random number in the usual way, and then transmit this random number to the client securely (e.g. through an HTTPS channel).

If you want the server and client to independently calculate this number, then:

  1. It's not really random, by definition; and
  2. It must depend on some other input in order to be repeatable (e.g. the MD5 hash of a particular file)
  3. What do you hope to gain from this parallel calculation, rather than just transmitting a number which is guaranteed to match?


You can try the following simple modulo randomiser.

public class SimpleRandom {
    private long seed;

    public SimpleRandom(long seed) {
        this.seed = seed;
    }

    public int nextInt(int n) {
        seed += 1111211111;
        return (int) ((seed >>> 8) % n);
    }

    public static void main(String... args) {
        SimpleRandom sr = new SimpleRandom(0);
        SortedSet<Integer> ints = new TreeSet<Integer>();
        while(ints.size() != 1000) {
            for(int i=0;i<500;i++)
                ints.add(sr.nextInt(1000));
            System.out.println("min: "+ints.first()+" max: "+ints.last()+" count: "+ints.size());
        }
    }
}

prints

min: 1 max: 998 count: 500
min: 1 max: 999 count: 682
min: 1 max: 999 count: 807
min: 0 max: 999 count: 925
min: 0 max: 999 count: 1000
0

精彩评论

暂无评论...
验证码 换一张
取 消