Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random.Next is not giving a random number

Tags:

c#

random

Hi
This how I used the random but it always gives "1" index to indexOfAChosenListCell.
When I debug it it shows different values, but on regular running I get the same move every time..
What is the problem with Random , it's static not random... :)

internal Square getAutomaticMove()                      
{
            List<Square> LegalMovesArray = GetLegalSquares();
            Random randomListCell = new Random();
            int indexOfAChosenListCell = 0;

            if (CheckForLegalSquares())    
            {
                 indexOfAChosenListCell = randomListCell.Next(LegalMovesArray.Count-1);
            }
like image 346
Mulder Avatar asked Mar 27 '11 00:03

Mulder


People also ask

What is the most Randomest number?

The short answer is that 17 is the most random number.

Does random next include 0?

Random. Next generates a random number whose value ranges from 0 to less than Int32. MaxValue. To generate a random number whose value ranges from 0 to some other positive number, use the Random.

Why is 17 the most common random number?

Seventeen is: Described at MIT as 'the least random number', according to the Jargon File. This is supposedly because in a study where respondents were asked to choose a random number from 1 to 20, 17 was the most common choice. This study has been repeated a number of times.


2 Answers

make randomListCell an instance variable and only initialize it once - otherwise you will keep getting the same numbers again.

From MSDN:

By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers.

like image 149
BrokenGlass Avatar answered Oct 19 '22 15:10

BrokenGlass


Random.Next(Int32)

Returns a nonnegative random number less than the specified maximum

So the largest number you'll ever get is Count - 2, probably not what you wanted.

like image 20
Ben Voigt Avatar answered Oct 19 '22 13:10

Ben Voigt