Click here to Skip to main content
15,667,422 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I would like to ask if there is any simple way to multiply the random generated number by the current millisecond? In my WPF Application I generate two random numbers in quick succession and it happens to me that in most cases they are the same, so I wondered if one of them could not be multiplied by the current millisecond.

I will be happy for any advice and and an idea, even if there is a better alternative.

Thank you

What I have tried:

This is my generator:
Random druhy = new Random();
            Random prvni = new Random();
            int maxprvni = 10;
            int maxdruhy = 10;
            int druhyc = druhy.Next(2, maxdruhy);
            int prvnic = druhyc * prvni.Next(1, maxprvni / druhyc);

I know how to display the current time:
Updated 12-May-21 23:23pm

The solution is simpler: don't use Random like that.
Declare a single Random instance at class level (static is fine) and use that for both values:
private static Random rand = new Random();
            int maxprvni = 10;
            int maxdruhy = 10;
            int druhyc = rand.Next(2, maxdruhy);
            int prvnic = rand.Next(1, maxprvni / druhyc);
When you create multiple Random instances, they will almost always produce the same sequence because they are initialised from the system clock. thus, using the clock again to try and "add extra randomness" isn't really going to help!

Just use a single Random instance and you'll be fine. You will get duplicates, but that's a product of your small phase space (ten items) rather than the generator itself.
Share this answer
Member 15170612 13-May-21 4:57am    
It's perfect. Thank you very much!!!
OriginalGriff 13-May-21 5:07am    
You're welcome!
Yeah that helped me too, thanks everyone :)
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900