从数组中选择随机字符串 [英] Pick Random String From Array
问题描述
如何从数组中随机选择一个字符串,但不选择相同的字符串两次.
string[] names = { "image1.png", "image2.png", "image3.png", "image4.png", "image5.png" };
这可能吗?我正在考虑使用
return strings[random.Next(strings.Length)];
但这有可能两次返回相同的字符串.还是我错了?我是否应该使用诸如 List
之类的其他东西来完成此操作.欢迎任何反馈.
最简单的方法(但对于大型列表来说速度较慢)是使用可调整大小的容器,例如 List
并在选择元素后将其删除.喜欢:
var names = new List{ "image1.png", "image2.png", "image3.png", "image4.png", "image5.png" };int index = random.Next(names.Count);var name = 名称[索引];名称.RemoveAt(index);返回名称;
当您的列表为空时,所有值都被选中.
一种更快的方法(尤其是当您的列表很长时)是在您的列表上使用改组算法.然后,您可以一次弹出一个值.它会更快,因为从 List
的末尾删除通常比从中间删除要快得多.至于改组,你可以看看这个问题了解更多详情.>
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:
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.
这篇关于从数组中选择随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!