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.
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.
The numpy. random. choice() function is used to get random elements from a NumPy array.
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.
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) ] ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With