Copy instance variable of type java.util.Random to create object in same state

前端 未结 3 1801
轮回少年
轮回少年 2021-01-20 05:58

I\'m implementing a simulated annealing (SA) algorithm, where I need to copy states (e. g. to remember best solution so far).

I implemented a copy method, since it\'

3条回答
  •  野性不改
    2021-01-20 06:28

    I think you should store in your State class, not only starting seed but also number of calls to nextInt() you already did. This is due to the intrisic fact that Random generates pseudo-random sequence of numbers. That is:

    A pseudo random number generator can be started from an arbitrary starting state using a seed state. It will always produce the same sequence thereafter when initialized with that state

    Let me explain show you with a sample first:

    public static void main(String[] args){
    
         Random r = new Random(42);      
         Random s = new Random(42);
    
         for(int i = 0; i < 5; i++){
           System.out.println("First random " +r.nextInt());
         }
    
         for(int i = 0; i < 5; i++){
           System.out.println("Second random " +s.nextInt());
         }
    
      }
    

    which result is:

    First random -1170105035
    First random 234785527
    First random -1360544799
    First random 205897768
    First random 1325939940
    Second random -1170105035
    Second random 234785527
    Second random -1360544799
    Second random 205897768
    Second random 1325939940
    

    Since both Random instances start with same seed, I always get the same sequence of numbers.

    So, when copying object you should init the new Random to the same seed of source (you already do this) and "consume" as much calls of nextInt() that you already used in source object (this is why you have to keep that number).

    After done this, calling the nextInt() on the copy will give you the same result that source object. I hope my code is enough to refactor yours and let you understand my solution.

    To understand better pseudorandom number generators (PRNG), also known as a deterministic random bit generators (DRBG), you can look at this Wikipedia article

提交回复
热议问题