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 best thing to do is just create a duplicate list, then as you randomly pick out a string, you can remove it from the duplicate list so that you can't pick it twice.
You can shuffle the array in a first step, and then simply iterate over the shuffled array.
This has the advantage of being O(n) compared to O(n^2) the
RemoveAt
based implementations have. Of course this doesn't matter much for short arrays.Check Jon Skeet's answer to the following question for a good(all orders are equally likely) implementation of shuffe: Is using Random and OrderBy a good shuffle algorithm?
Use the below utility method
Then call the below way
You would need to keep track of the ones you have used, preferably in a
List
if you don't want/can't to modify the original array. Use awhile
loop to check that it hasn't been used, and then add it to the "used" list.The logic you could use is as follows:
1) Pick a random integer over the range equal to the length of your array. You can do this using the System.Random class.
2) Use the string corresponding to that array index
3) Delete the item with that index from the array (may be easier with a list)
Then you can pick again and the same string won't appear. The array will be one element shorter.