Ive taken over some prize drawing code.
I can see the person is using a Random number to order them by but is this actually going to be random as i cant see any place where he has done oRand.Next(); Does the default Random generate an actual random number.
Random oRand = new Random();
var res = (from l in listNew.AsQueryable<Participant>() //entities.Participant
where l.Status != 0
select l).AsEnumerable().OrderBy(p=>oRand);
Does the default Random generate an
actual random number.
In the example code you are ordering by the "RandomNumberMaker" (i.e. the same value for all values), not by random numbers.
This is quickly tested by comparing this code in LINQPad (which yields the numbers 1 to 1000 in natural order).
void Main()
{
Random oRand = new Random();
var res = Enumerable.Range(1, 1000).OrderBy(p=>oRand);
res.Dump();
}
with this code (which orders the numbers 1 to 1000 in pseudorandom order):
void Main()
{
Random oRand = new Random();
var res =Enumerable.Range(1, 1000).OrderBy(p=>oRand.Next());
res.Dump();
}
For an intro to how random .NET random really is, check out this article which has the advantage of starting with this great comic:
(source: csharpcity.com)
I think you need oRand.Next() to get random numbers. This looks like it would end up ordering them by the Random object. I don't see how using oRand by itself would result in the lambda expression calling Next().
In any case, when you use oRand = new Random(); oRand.Next();, you get pseudorandom numbers using time as a seed. This means that there is a sequence of numbers that is the same every time, and the one you start with depends on the time -- this is usually done with a function that you pass the last random number to get the next one and it has a very long period and the numbers have a random feel (so it's not just f(x) => x+1 or something like that).
This may not be good enough, but it is "random" for some definition of random.
Related
how can I get two strings from two arrays randomly. I have something, but It doesn't pick randomly.
string[] firstNames = { "John", "Michael", "Victor", "Mark", "Alex", "Steven", "Zack", "Howard", "Xzavier", "Brendan", "Dustin", "Carl" };
string[] lastNames = { "Adams", "McGregor", "Piasta", "Semmel", "Laris", "Sever", "Bourque", "Percy", "Shanabarger", "Bobak", "Adair" };
string[] shuffled = firstNames.OrderBy(n => Guid.NewGuid()).ToArray();
string[] shuffled2 = firstNames.OrderBy(n => Guid.NewGuid()).ToArray();
Random firstn = new Random();
Random lastn = new Random();
int index = firstn.Next(firstNames.Length);
int index2 = lastn.Next(lastNames.Length);
Console.WriteLine($"The random name is {firstNames[index]}" + $" {lastNames[index2]}");
I am trying to make a random full name generator. I have tried this code multiple times and the results were: John Adams, Victor Piasta, and so on! And as you can see they are not random.
Looks pretty random to me..
With 150 iterations you still get a performance of roughly 90 of 132 possible combinations.
Testing code:
HashSet<string> names = new HashSet<string>(150);
Random rndm = new Random();
for (int i = 0; i < 150; i++)
{
names.Add($"{firstNames[rndm.Next(firstNames.Length)]} " +
$"{lastNames[rndm.Next(lastNames.Length)]}");
}
Console.WriteLine($"{names.Count} / {firstNames.Length * lastNames.Length}");
Console.ReadKey();
Don't forget that true random is not possible to simulate... so you will always have some kind of repetitive distribution with higher numbers.
Random works slightly different in .NET-Framework to .NET-Core
In .NET Framework, the default seed value is time-dependent. In .NET Core, the default seed value is produced by the thread-static, pseudo-random number generator.
From: https://learn.microsoft.com/en-us/dotnet/api/system.random?view=netcore-3.1#Instantiate
In the .NET-Framework only, on most Windows systems, Random objects created within 15 milliseconds of one another are likely to have identical seed values.
Use a single Random-instance on .NET-Framework to avoid this behaviour.
Just change to below so that you are using the same Random instance for both
int index2 = firstn.Next(lastNames.Length);
Random does not actually generate random numbers, but pseudo-random numbers. That means, you need a starting value, the so-called seed. From that value the first number is calculated. From that, one could calculate another number, and so on. These numbers look like random, but actually they are determined by the seed. If you have the same seed, you always get the same sequence of numbers.
Your Random class has actually a constructor where you can deliver a seed. You can try it out here: https://dotnetfiddle.net/0bHDNg For the same seed, you will always get the same sequence of numbers.
If you use the constructor without a parameter, the current time is taken as the seed. This has the big advantage, that you always get a different sequence of numbers when you restart the program. But in your example, you have a problem: If the time between creating the two instances of Random has not changed, because the computer is so fast, they will have both the same seed and thus both the same sequence of numbers. That's why index and index2 both have the same value. Just use the same instance of Random for generating both indices, and they don't have necessarily the same value:
Random random = new Random();
int index = random .Next(firstNames.Length);
int index2 = random .Next(lastNames.Length);
Console.WriteLine($"The random name is {firstNames[index]}" + $" {lastNames[index2]}");
If I create a Random() with a different starting seed every time will the first number in the generator be unique every time, or is there a point in which the first number will start repeating?
Example:
var random1 = new Random(1);
var value1 = random1.Next();
var random2 = new Random(2);
var value2 = random2.Next();
var random3 = new Random(x);
var value3 = random3.Next();
where value1 != value2 != value3;
EDIT: Fixed variable names
I have tested seeds of 0-80,000,000, I am just wondering if they are unique from 0-int.Max, or if the first 80,000,000 are unique by accident
Generally, I don't think there is any requirement that pseudorandom generators should generate unique numbers given unique seeds.
The only think it happens is that, given a seed, the generator will always generate the same number sequence (obtained by calling multiple times the next method) and the sequence will repeat at some point.
However, the C# Random class uses a subtractive generation algorithm, where the next random number is generated basing on previous numbers of the sequence. Hence, there may be some kind of dependency between the number and the seed, which makes the random number generator to generate unique numbers every time the seed is changed.
If you want to be sure, either try it yourself with seeds from int.MinValue to int.MaxValue, or check the C# implementation here
https://referencesource.microsoft.com/#mscorlib/system/random.cs
I'm working on Pong in C# w/ XNA.
I want to use a random number (within a range) to determine things such as whether or not the ball rebounds straight, or at an angle, and how fast the ball moves when it hits a paddle.
I want to know how to implement it.
Use the Random class. For example:
Random r = new Random();
int nextValue = r.Next(0, 100); // Returns a random number from 0-99
Unless you need cryptographically secure numbers, Random should be fine for you... but there are two gotchas to be aware of:
You shouldn't create a new instance every time you need one. If you create an instance without specifying a seed, it will use the current time as the seed - which means if you create several instances in quick succession, many of them will produce the same sequence of numbers. Typically you create a long-lasting instance of Random and reuse it.
It's not thread-safe. If you need to generate random numbers from multiple threads, you should think about having one instance per thread. Read this blog post for more information - but make sure you read the comments as well, as they have very useful information.
Random rnd = new Random();
rnd.Next(minValue, maxValue);
i.e.
rnd.Next(1,10);
Use the Random object's Next method that takes a min and max and returns a value in that range:
var random = new Random();
int randomNum = random.Next(min, max);
While you can use the Random class like all the other are suggesting, the Random class only uses psuedo-random number generation. The RandomNumberGenerator, which can be found in the System.Security.Cryptography namespace, creates actual random numbers.
How To Use:
RandomNumberGenerator rng = RandomNumberGenerator.Create();
byte[] rand = new byte[25]; //Set the length of this array to
// the number of random numbers you want
rng.GetBytes(rand);
More Info: http://msdn.microsoft.com/en-us/library/system.security.cryptography.randomnumbergenerator(v=VS.80).aspx
Here is my random generator
private static Random rnd = new Random(Environment.TickCount);
private int RandomNum(int Lower, int Upper)
{
return rnd.Next(Lower, Upper);//MyRandomNumber;
}
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 9 years ago.
having an issue generating random numbers in a loop. Can get around it by using Thread.Sleep but after a more elegant solution.
for ...
Random r = new Random();
string += r.Next(4);
Will end up with 11111... 222... etc.
Suggestions?
Move the declaration of the random number generator out of the loop.
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, ...
Source
By having the declaration in the loop you are effectively calling the constructor with the same value over and over again - hence you are getting the same numbers out.
So your code should become:
Random r = new Random();
for ...
string += r.Next(4);
Random r = new Random();
for ...
string += r.Next(4);
new Random() will initialize the (pseudo-)random number generator with a seed based on the current date and time. Thus, two instances of Random created at the same date and time will yield the same sequence of numbers.
You created a new random number generator in each iteration and then took the first value of that sequence. Since the random number generators were the same, the first value of their sequences was the same. My solution will create one random number generator and then return the first, the second, etc... value of the sequence (which will be different).
I found a page in Chinese that said the same with the time: http://godleon.blogspot.hk/2007/12/c.html, it said if you type like this:
Random random = new Random(Guid.NewGuid().GetHashCode());
you MAY get a random number even in a loop! It solved my question as well!
You should be using the same Random instance throughout instead of creating a new one each time.
As you have it:
for ...
Random r = new Random();
string += r.Next(4);
the seed value is the same for each (it defaults to the current timestamp) so the value returned is the same.
By reusing a single Random instance like so:
Random r = new Random()
for ...
string += r.Next(4);
Each time you call r.Next(4) the values are updated (basically a different seed for each call).
Move the Random r = new Random(); outside the loop and just call next inside the loop.
For a part of a program i need the following 2 methods.
The first method listed will generated a random number.
where the 2nd method will "call" this method to fill the array.
The array has a max. number of elements defefined on 100 (and all the random generated numbers should be between 1-100).
The problem is i never get random numbers generated. (either i get 100 x the same value, 3 random numbers divided over the 100 max. elements of the array, or the same value 100 times all over again).
The problem should be in the first method, but i cannot seem to figure out the problem.
Been staring at this for quite some time now...
The problem should be with the return, cause it DOES create random generated numbers. But how do i return the generated value every time? (the int method has to be called with the 3 parameters).
private int ValidNumber(int[] T, int X, int Range)
{
for (byte I = 0; I < T.Lenght; I++)
{
Random RndInt = new Random();
X = RndInt.Next(1, Range+1);
}
return X;
}/*ValidNumber*/
public void FillArray(int[] T, int Range)
{
for (byte I = 0; I < T.Length; I++)
{
T[I] = ValidNumber(T, I, Range);
}
}/*FillArray*/
Console code:
public void ExecuteProgram()
{
ClsBereken Ber = new ClsBereken();
//const byte Range = 100;
const int Max = 100;
int[] T = new int[Max];
Ber.FillArray(T, Max);
DisplayArray(T);
}/*ExecuteProgram*/
private void DisplayArray(int[] T)
{
for (byte i = 0; i < T.Length; i++)
{
Console.Write("{0,4} ", T[i]);
}
Console.WriteLine();
}/*DisplayArray*/
Any help alot appreciated.
Kind Regards.
Re-use the Random instance. NOTE I've edited this to show passing the Random instance down, but I'm really not sure what ValidNumber is trying to do - it looks like it is juts burning up CPU cycles? I would suggest you can remove ValidNumber completely (and just use the next value from the Random in FillArray), but presumably you are trying to do something here - I'm just not sure what!
private int ValidNumber(int[] T, int X, int Range, Random random)
{
for (byte I = 0; I < T.Lenght; I++)
{
X = random.Next(1, Range+1);
}
return X;
}/*ValidNumber*/
public void FillArray(int[] T, int Range)
{
Random random = new Random();
for (byte I = 0; I < T.Length; I++)
{
T[I] = ValidNumber(T, I, Range, random);
}
}/*FillArray*/
When you create a Random, it is "seeded" using the system clock, but this is rounded heavily. If you create lots of Random in a tight loop, they all get the same "seed", so they all create the same next number.
If necessary you could move the Random further out (if you have other loops), or make it static (but if you do that you need to worry about synchronization too).
The problem is that you are reinitializing rndint over and over.
take the line:
Random RndInt = new Random();
and move it in front of the loop and see if that fixes it.
When you initialize a random object, it is assigned a seed (probably based on the time), and that seed is used to generate a series of seemingly random values. However, if you plug in the same seed to two random objects, you will get the same series of random numbers.
So, what is happening in your code is you are initializing a new random object with a seed, and then asking for the first random number in its series. Then, you are initializing another random object (even though it is assigned to the same name, it is a new object) and it is getting the same seed, and you are again asking for the first random number in the series. So naturally, you are getting the same random number over and over.
You are continuously creating an new Random object. I'm afraid this is seeded (randomized) by the timestamp of creation. Since this is really fast and happens multiple times, the seed is the same, and so is the result of the call RndInt.Next(1, Range+1);.
By the way, even though not incorrect, it's not a common practice in c#.net to start with a capital letter on names of local variables and parameters.
Any random number generation algorithm* is not truly random; it is simply a deterministic algorithm that has been specifically designed to output numbers that resemble randomness. (See Pseudorandom number generator.) Since the algorithm is deterministic, its output is completely dependent upon a starting "seed" value.
The Random class in .NET has two constructors: one which takes an integer seed, and another which takes no parameters. This one bases its seed off the current time.
From this information perhaps you can guess why creating a new Random instance for every value in your array results in the entire array being filled with the same number: every time you construct a Random object within a very small time frame, it will have the same seed value, which means it will generate identical output to another Random object constructed within the same time frame.
As Marc Gravell has already indicated, you should be using only a single Random instance to generate a sequence of random numbers.
*Well, almost any. I believe there are hardware implementations of random number generators that factor in random noise (taken from the surrounding environment) and may therefore be considered "truly" random. Whether you believe these are actually random
depends on your personal definition of "random" and whether or not you believe that we live in a deterministic universe.
You can pass Random() a seed but if you send it the same seed number you will get the same results. The way you are using it
Random rnd = new Random();
Is using an auto-generated seed based on time. But you may not get seemingly random results if you don't at least sleep for a second. (Source http://msdn.microsoft.com/en-us/library/system.random(VS.71).aspx)
As everyone has mentioned here already your biggest issue is the fact you keep recreating the random object each iteration.