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.
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: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