拾取随机字符串从Array [英] 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.
推荐答案
最简单的方法(但速度慢于大型列表)是使用像列表中的一个可调整大小的容器
和采摘后删除元素。这样的:
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.
这篇关于拾取随机字符串从Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!