Random long, can it be twice in a row the same number

后端 未结 4 1507
我在风中等你
我在风中等你 2021-02-13 10:42

I was wondering with the current java 1.7 implementation of the Random class, is it possible for the code below to generate two times the same random long?

Rando         


        
4条回答
  •  遇见更好的自我
    2021-02-13 10:52

    No, getting two identical longs in a row with this algorithm is impossible.

    While people were writing long posts about math and other wizardry, I went the code monkey route and brute forced the 2^48 possible seeds over the weekend. No two longs produced in a row were ever equal for any seed.


    long int seed = 0;
    
    int next(int bits){
        seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
        return (int) (seed >> (48 - bits));
    }
    long int nextLong(){
        return ((long int) next(32) << 32) + next(32);
    }
    
    int main(int argc, char** argv) {
      long int step = atoi(argv[1]);
      long int i = step << 32;
      long int end = (step+1) << 32;
      while(i < end) {
        seed = i;
        if(nextLong() == nextLong()) {
          printf("Found seed %ld\n", i);
          return 0;
        }
        ++i;
      }
      printf("No seed in %ld\n", step);
      return 1;
    }
    

    then

    echo {0..65535} | xargs -n 1 -P 12 ./executable
    

提交回复
热议问题