+ 3
Randomly picking up a value in an array
I wrote a small programme that randomly picks up and displays a number from a small array. I'm trying to figure out a way to pick up a random number in a bigger array. Has anyone got any convenient solution to do that ? https://code.sololearn.com/cakXzXVyZIkq/?ref=app
4 ответов
+ 12
This works for arrays of any size.
int [] tableau = new int [5] {8,1,5,6,2};
Random chiffre = new Random ();
int j = chiffre.Next(5);
Console.WriteLine(j);
Console.WriteLine(tableau[j]);
+ 9
Thanks Sir Krishna! Anyway you may:-
☑ Omit the 5 in the square bracket since the array size was fixed during initialization.
☑ Replace the 5 in Next method with tableau.Length
and it will work for any array size! 😉
+ 7
In two lines...
int [] array = {1, 2, 3, 4, 5};
Console.WriteLine(array[new Random().Next(-1,array.Length)]);