Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique random number generation

Tags:

java

I'm looking for way to generate unique random numbers based on current time using java. I'm a c++ programmer and in c++ I usually seed the Random with time so at each specific moment I can get a unique random number and it works like this :

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

In java I found that I can use the same method by seeding the random number with time like this:

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

Here is the problem I have used all the methods I found over the internet for generating a random number in java but none of them were truly random and they ranged from negative to positive numbers. For example:

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 than in C++.

I just want to know what the best way to do this in java is, some like or very close to TAC number generation.

like image 308
Loop Masters Avatar asked Feb 21 '23 08:02

Loop Masters


1 Answers

Java's and C++ random numbers are both pseudorandom. Of course the algorithms are different, so the results are different too.

If you would like a random number generator that is strong enough to use for cryptography, you can use SecureRandom: its interface is less intuitive, and it consumes more CPU, but the quality of its output is much higher than of a regular PRNG of Java,

like image 156
Sergey Kalinichenko Avatar answered Feb 22 '23 21:02

Sergey Kalinichenko