user2509901
user2509901

Reputation:

Picking a random element from a Multidimensional Array

Please Does anyone know how to pick a random element from an array?

I know how to implement on normal Variables

Random rnd = new Random();
int no = rnd.Next(30);
Console.WriteLine(no);

but i need to implement it on an array.

Upvotes: 0

Views: 2353

Answers (1)

Mike Precup
Mike Precup

Reputation: 4218

Here's an example of how to pick a random element from an array.

int[] possible = new int[] { 0, 5, 10, 15 };
Random r = new Random(); 
int a = possible[r.Next(possible.length)];

However, I should note that if you call this repeatedly, make sure you only call the last line multiple times. Calling the second line every time could result in repeated results, as Random() uses the current time as a seed. If the time hasn't changed, you'll get the same result multiple times.

At OP's request: on a two dimensional array:

//Assuming possible is an int[,]
Random r = new Random(); 
int a = possible[r.Next(possible.GetLength(0)), r.Next(possible.GetLength(1))];

Upvotes: 2

Related Questions