Unique random number generation

I am looking for a way to generate unique random numbers based on current time using java. I am a C ++ programmer, and in C ++ I usually pick up Random over time, so at any given moment I can get a unique random number, and it works as follows:

sRand((time)Null); x=Rand(); 

In java, I found that I can use the same method by sowing a random number over time as follows:

 Random rand = new Random(System.currentTimeMillis()); 

Here is the problem, I used all the methods that I found on the Internet to create a random number in java, but none of them were really random, and they ranged from negative to positive numbers. For instance:

 Random rand = new Random(System.currentTimeMillis()); int x=rand.nextInt(); // or long or float ... 

What I get is a series of not truly random numbers, and the result is really different from the result in C ++.

I just want to know that the best way to do this in java is something like or very close to generating a TAC number.

+4
source share
2 answers

Random numbers Java and C ++ are pseudorandom . Of course, the algorithms are different, so the results are also different.

If you need a random number generator that is strong enough for use in cryptography, you can use SecureRandom : its interface is less intuitive and it consumes more processor, but its output quality is much higher than that of regular PRNG Java.

+8
source

If you want to generate a random number, the easiest way is to use the new Random (). nextInt () could possibly wrap it in Math.abs () to avoid negatives. If you need a unique number, you can use UUID.randomUUID ().

0
source

Source: https://habr.com/ru/post/1414516/


All Articles