jeudi 29 août 2019

Ensuring No Random Sequence Is Repeated Indefinitely

I'm attempting to generate a random string of length X. I want to ensure that no two sequences are ever identically produced, even if this code is being run on multiple machines and at the same time.

"list" is the list of characters I'm using, "min" and "max" are the range of indexes, and "length" is the desired length of the String.

Currently, I am using System.nanoTime() as the seed for the Random object. While I realize it is likely improbable for 2 machines to run at the exact same time down to the nano second and produce the same output, I want to make this a foolproof solution.

How can I increase the randomness of this code so that no 2 strings will ever be the same without increasing the length of the string or increasing the number of characters available to be included in the string?

String seq = "";
for (int i = 0; i < length; i++)
    {
      Random rnd = new Random();
      rnd.setSeed(System.nanoTime());
      int randomNum = rnd.nextInt((max - min) + 1) + min;
      seq = seq + list[randomNum];
    }

return seq;




Aucun commentaire:

Enregistrer un commentaire