How Java random generator works?

前端 未结 4 1157
天涯浪人
天涯浪人 2021-01-04 09:36

I wrote program that simulates dice roll

    Random r = new Random();
    int result = r.nextInt(6);
    System.out.println(result);

I want

4条回答
  •  被撕碎了的回忆
    2021-01-04 10:30

    They're pseudorandom numbers, meaning that for general intents and purposes, they're random enough. However they are deterministic and entirely dependent on the seed. The following code will print out the same 10 numbers twice.

    Random rnd = new Random(1234);
    for(int i = 0;i < 10; i++)
        System.out.println(rnd.nextInt(100));
    
    rnd = new Random(1234);
    for(int i = 0;i < 10; i++)
        System.out.println(rnd.nextInt(100));
    

    If you can choose the seed, you can precalculate the numbers first, then reset the generator with the same seed and you'll know in advance what numbers come out.

提交回复
热议问题