random nr for 000001 - 000100 - c#

How to generate 6 dig random number (within specific interval)? would
Random rand = new Random();
still work in this case? (e.g rand.Next(000000, 000101)) I need to keep 6dig format
asp.net C#

You need to separate the numeric value from the text representation. 000101 is the same number as 101. Pick the random number using Next(min, max) and then format it however you want, e.g. with value.ToString("000000") or value.ToString("D6") (whichever you find more readable).
Note that you should take care when using Random - there are a few subtle issues. (In particular, you very rarely want to actually create a new instance with the parameterless constructor in the line of code before you use it...)

Try this:
string.Format("{0:000000}", rand.Next(0, 100));

A number doesn't have a format at all, you give it a format when you convert the number to a string. So, the random part of the code is the same, you just format the number in a specific way:
Random rnd = new Random();
string formatted = rnd.Next(1, 101).ToString("000000");
Note: The lower bound for the Next method is inclusive and the upper bound is exclusive. Next(0, 101) would give you a result between 000000 and 000100.

Related

Adding Seed to C# random number always yields same result

whenever I have two random numbers being generated like so :
Random rand1 = new Random();
Random rand2 = new Random(23);
the second random number's value never changes
while rand1 varies on each load, rand2 always presents the value 396.
Am I declaring the seed wrongly?
The second random value never change entirely by design. Moreover, if you store the first 100 or 1000 random numbers after seeding your generator to a fixed number, you would get the same sequence every time you run the program.
Seeding a pseudorandom number generator is designed specifically to let you produce a repeatable sequence of random numbers. This is very useful for testing your code that needs to use random numbers, but you want repeatable behavior for testing purposes.
In situations when you do not need to produce the same pseudorandom sequence again and again, you seed your random number generator to some changing number, for example, the current system time.

Random number generator generating same numbers each time application is ran [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 8 years ago.
I know there are multiple times this question has been put forth but none of those solutions worked for me.
First I did this in my method called RandomNumGenerator(items)
List<int> randNum = new List<int>();
foreach (var item in items)
{
randNum.Add(new Random(1000).Next());
}
This always gave me the same number, and then after looking at this answer I did this:
Random rnd = new Random(1000);
foreach (var item in items)
{
randNum.Add(rnd.Next());
}
This gave me the numbers as below
325467165
506683626
1623525913
2344573
1485571032
Now while that is fine for every iteration of the loop, the problem here is, when I stop and re-run the application, I get the same numbers I got earlier all over again.
325467165
506683626
1623525913
2344573
1485571032
Is this behavior during debugging only or will I have the same issue every time I call the RandomNumGenerator?
You are seeding the Random instance always with the same seed 1000 here:
Random rnd = new Random(1000);
this will not do that since the current time is used as seed:
Random rnd = new Random();
Have a look at the constructor which takes an int.
Providing an identical seed value to different Random objects causes
each instance to produce identical sequences of random numbers.
As per MSDN.
public Random(
int Seed
)
Seed
A number used to calculate a starting value for the pseudo-random number sequence. If a negative number is specified, the absolute value of the number is used.
The reason for most beginner's mistakes involving RNGs (random number generators), is the lack of understanding about what the "seed" is and what it does.
So what is a "seed"?
The Random class is a class for generating pseudo-random numbers - or numbers that appear to be random. They are usually a mathematical function, that uses a parameter - the "seed" - to generate a sequence of numbers that appear to be random.
In the case of new Random(1000), the first 5 nonnegative random integers are
325467165
506683626
1623525913
2344573
1485571032
In your first code, you create a new sequence of pseudo-random numbers with the same seed every time you need a random number, so obviously your array is filled with the same number: 325467165, which happens to be the first nonnegative integer generated by new Random(1000).
This also explains why your second code always generates the same sequence of pseudo-random numbers every time your application is launched.
To ensure your app always generate different pseudo-random sequences, you need to use a different seed each time. By far the easiest way to ensure that, is to take your time, literally.
Random rnd = new Random(DateTime.UtcNow.Millisecond);
// Taking the millisecond component, because it changes quickly
Luckily, you don't have to type this much, because the default constructor for the Random class already does something similar to that.
Random rnd = new Random(); // Much simpler, isn't it?
Keep in mind that the Random class is not thread safe; if multiple threads attempt to access the same Random object concurrently, your RNG will return only 0 for the remaining of its lifetime.
Another thing to note, is that creating multiple Random objects one after the other - even when using time as the seed - can lead to the same sequence of pseudo-random numbers.
Random r1 = new Random();
Random r2 = new Random();
Random r3 = new Random();
Random r4 = new Random();
In the above code, chances are very high, that r1, r2, r3 and r4 will all generate the same sequence.
How is that possible?
Well, (un)fortunately, CPUs are blazing fast. A 1 GHz CPU can execute about 1 billion instructions per second (give or take); that's 1 instruction every 1 nanosecond - or 1 instruction every 1 millionth of a millisecond.
Creating a new Random object might require quite a lot of instructions, but most definitely less than a million of them.
So why do we need to manually define a seed, if using the clock's current millisecond count is what we "all" want and is already the default?
Because it can be very useful for keeping multiple terminals in sync.
Imagine a game, where important phenomena randomly appear, such as a change in weather that could completely overturn the game. You wouldn't want only one side to suffer from fog, while the rest still profits from clear weather, right?
Of course, you could have the server or the host generate random weather changes and notify the players about it; or you could define a seed before the game starts, and use that seed to ensure the same "randomness" across all players throughout the game.
Isn't coding fun?
You need to change this:
Random rnd = new Random(1000);
to
Random rnd = new Random();
From the Random Constructor docs:
The default seed value is derived from the system clock and has finite
resolution. As a result, different Random objects that are created in
close succession by a call to the default constructor will have
identical default seed values and, therefore, will produce identical
sets of random numbers. This problem can be avoided by using a single
Random object to generate all random numbers. You can also work around
it by modifying the seed value returned by the system clock and then
explicitly providing this new seed value to the Random(Int32)
constructor. For more information, see the Random(Int32) constructor.
Key concept is random seed - the initial piece of data from which the Random derives everything else. If the seed is the same then "random" sequence will be the same.
By default the seed is set to zero, which obviously leads to repeating sequences amongst program runs.
To avoid that, you can construct your Random like this:
Random rnd = new Random();
... which is, under the hood, is:
Random rnd = new Random(Environment.TickCount);
This will init the Random object with amount of milliseconds from the OS start. This will be different each time your program starts, so you'll get different random sequences each time.
Random .Next() method generates pseudo-random number. You should Declare and initialize a random object instead of creating each time new object. And no need to use any Cryctography .. :)
You should use class level random variable. If you used a new Random at the method level as a local , the time-dependent seed would repeat itself generating identical sequence of random numbers.
class Program
{
static Random _r = new Random();
static void Main()
{
// use _r variable to generate random number
}
}

3 digit random number in C#

Is there a better way to generate 3 digit random number than the following:
var now = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture);
string my3digitrandomnumber = now.Substring(now.Length - 7, 3);
Thanks..
Yes - your current code isn't random at all. It's based on the system time. In particular, if you use this from several threads at the same time - or even several times within the same thread in quick succession - you'll get the same number each time.
You should be using Random or RandomNumberGenerator (which is more secure).
For example, once you've got an instance of Random, you could use:
int value = rng.Next(1000);
string text = value.ToString("000");
(That's assuming you want the digits as text. If you want an integer which is guaranteed to be three digits, use rng.Next(100, 1000).)
However, there are caveats around Random:
You don't want to create a new instance each time you use it; that would also be time based unless you specify a seed
It's not thread-safe
So ideally you probably want one per thread. My article on randomness talks more about this and gives some sample code.
int r = (new Random()).Next(100, 1000);
You can use the Random class and call Next(10) three times.
Well, firstly that's an odd setup you have there, why do you first get the date?
You should use this to get a number of 3 digits (less than 1000).
Random rand = new Random(); // <-- Make this static somewhere
const int maxValue = 999;
string number = rand.Next(maxValue + 1).ToString("D3");
The maxValue + 1 is because the paramter for Random.Next(int) is an exclusive upper bound, meaning that the number returned will always be less than the parameter. It can never be equal to it.
new Random.NextDouble() * 1000

"new Random(x)" always generates the same numbers? [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 9 years ago.
I am trying to get a unique random number but i always get the same number every time i run the code. i will get 14 first then 6 but my list for holding all the used numbers doesn't seem to work.adding the 14 manually works but when i add randInt it doesn't work.
const int numCards = 32;
List<int> usedCards = new List<int>();
int randInt = 0;
Random rand = new Random(numCards);
usedCards.Add(14);
do
{
randInt = rand.Next(0, numCards);
MessageBox.Show(randInt.ToString(), "End Game", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
while (usedCards.Contains(randInt));
usedCards.Add(randInt);
Replace:
Random rand = new Random(numCards);
with
Random rand = new Random();
Supplying a fixed seed value (numCards always has the same value) in the Random constructor call will result in a predictable, reproducible sequence which is always the same for the same seed value, just like this (not quite but still the point is valid):
For example using a fixed seed of 1 and drawing 10 numbers ranging from 0 to 100, on my machine always produces the sequence
24,11,46,77,65,43,35,94,10,64
Using no seed value on the other hand, the sequence becomes unpredictable.
Without a seed value passed in, Random will generate a new seed value based on the current time, that's what you want to get a new sequence of random numbers - provided you don't initialize it again in fast order, that's why you should re-use Random instances instead of re-creating them every time.
Random Class
If you specify a seed value to the Random class constructor, it will generate the same sequence every time. The algorithm to produce the random number sequence is deterministic.
If you use the constructor without parameters, the Random object will use a seed value on the current time, so each Random object instantiated using this constructor will have a different sequence of random numbers as long as the time seed value is different which is likely.
You can still get the same sequence of numbers from two different Random objects if they are initialized very close in time to each other.
Random Constructor

generating completely random even numbers with C#

is there any good method to generate random even numbers with C#? I came up with this code:
Random RandString = new Random(0);
code:
private void button6_Click(object sender, EventArgs e)
{
int min = 0;
int max = 50;
int rand = RandString.Next(min, max-1);
while (rand % 2 == 1) // odd
{
rand = RandString.Next(min, max-1);
}
textBox4.Text = "" + rand;
}
Problems with this code:
my current solution might not be the fastest of all
very often, numbers that are generated by this method are repeated with the same sequence! For example after 5 iterations I can get: 8, 10, 20, 30, 16. After more clicking (for like 15 seconds) I can get 10, 30, 20 in a row or 30, 20, 10.. I'm not sure, but that's NOT what I call "random".
so is there any way to deal with the problem that I've described, or is there any other method?
textBox4.Text = (2 * rand.Next(min / 2, max / 2)).ToString();
even easier would be to take your result and multiply it by 2
private void button6_Click(object sender, EventArgs e)
{
int min = 0;
int max = 25;
int rand = RandString.Next(min, max-1)*2;
textBox4.Text = rand.ToString();
}
Random random = new Random();
int nextnum = random.Next(min/2,max/2) * 2
You could use the RNGCryptoServiceProvider to get a "more random" (which is a silly term I admit) number. There is a nice eample on MSDN's documentation page.
As others recommended, you can just multiply the result with 2 to get an even number.
There are a number of flaws in your approach.
First of all, Random from .NET isn't completely random in the cryptographic sense AFAIK, but it should be much much better than the results you report. Most likely, you are creating a new Random object on every iteration of your loop; since the current system time is used to seed the RNG, you will get the same sequences of pseudo-random numbers if you do runs very short after one another. Instead, create one instance of Random at startup, and keep it around for as long as possible.
Then, creating an even number from a random integer is much easier than looping until you find one that happens to be even: just generate one random number and clear the least significant bit: myRand.Next(min, max-1) & ~1;. A decent RNG has a uniform distribution over all of its bits, so clearing any bit shouldn't reduce entropy by more than, well, one bit.
Getting back to the 'completely random' part: Random provides a pseudo-random number generator. It is seeded once, based on a value that is somewhat random-ish (the least-significant parts of the current system time), but given the same seed, the RNG will reliably and deterministically produce the same numbers on every run. If you want true randomness (a.k.a. 'entropy'), you'd be surprised how hard it is to produce it on a machine that was built for deterministic calculations. UNIX and Unix-like systems typically offer a pool of entropy through a special kernel-generated file (/dev/random), using things like hard disk access timing, network noise, and whatever other sources of actual randomness they can find, and distillate those into a uniform distribution using fairly complicated calculations. Windows can probably do the same, but I am unaware of any API for this in either .NET or the classic win32 API.

Categories

Resources