Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick Random String From Array

How do I go about picking a random string from my array but not picking the same one twice.

string[] names = { "image1.png", "image2.png", "image3.png", "image4.png", "image5.png" }; 

Is this possible? I was thinking about using

return strings[random.Next(strings.Length)]; 

But this has the possibility of returning the same string twice. Or am I wrong about this? Should I be using something else like a List to accomplish this. Any feedback is welcome.

like image 200
atrljoe Avatar asked Jul 14 '11 14:07

atrljoe


People also ask

How do I randomly select a string from a list in Python?

Use the random. sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.

How do you select a random value from an array in Python?

The numpy. random. choice() function is used to get random elements from a NumPy array.


2 Answers

The simplest way (but slow for large lists) would be to use a resizeable container like List and remove an element after picking it. Like:

var names = new List<string> { "image1.png", "image2.png", "image3.png", "image4.png", "image5.png" };  int index = random.Next(names.Count); var name = names[index]; names.RemoveAt(index); return name; 

When your list is empty, all values were picked.

A faster way (especially if your list is long) would be to use a shuffling algorithm on your list. You can then pop the values out one at a time. It would be faster because removing from the end of a List is generally much faster than removing from the middle. As for shuffling, you can take a look at this question for more details.

like image 200
Etienne de Martel Avatar answered Oct 02 '22 22:10

Etienne de Martel


Try this code below

string[] Titles = { "Excellent", "Good", "Super", "REALLY GOOD DOCTOR!", "THANK YOU!", "THE BEST", "EXCELLENT PHYSICIAN", "EXCELLENT DOCTOR" };  comments_title.Value=Titles[new Random().Next(0,Titles.Length) ] ; 
like image 28
Bharat Kumar Avatar answered Oct 02 '22 21:10

Bharat Kumar