0

hi there,

i want to randomly pick an element from an array, so i used the following code.

Random rndCell = new Random((int)DateTime.Now.Ticks);

while (true)
{
    rndCell.Next(aCells.Length);
    int rndIndex = Convert.ToInt32(rndCell.ToString());
    if (aCells[rndIndex] != null)
    {
        aCells[rndIndex] = SOMETHING;
        // DO SOMETHING ELSE WITH rndIndex...
        break;
    }
}

it raises an error while trying to convert the random number to integer. does anyone knows how to do it?

best regards,
Sean

2
Contributors
1
Reply
5
Views
8 Years
Discussion Span
Last Post by ddanbe
0

Most of the time you do not want to provide a seed to a random number generator. This will have the same effect as your code:
Random rndCell = new Random();
Line 5 and 6 can be replaced with this :
int rndIndex = rndCell.Next(aCells.Length-1);
If your array has a lenght of 10, this will produce numbers from 0 to 9! (The indexes of your array! Not 0 to 10, 10 is not an index!)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.