+ 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

29th Sep 2017, 9:19 AM
Tho5mas
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]);
29th Sep 2017, 9:44 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 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! 😉
29th Sep 2017, 9:58 AM
Zephyr Koo
Zephyr Koo - avatar
+ 7
In two lines... int [] array = {1, 2, 3, 4, 5}; Console.WriteLine(array[new Random().Next(-1,array.Length)]);
29th Sep 2017, 4:18 PM
Vukan
Vukan - avatar