简体   繁体   English

从数组中选择随机字符串

[英]Pick Random String From Array

How do I go about picking a random string from my array but not picking the same one twice.我如何 go 关于从我的数组中选择一个随机字符串但不选择两次相同的字符串。

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.我是否应该使用像List这样的其他东西来完成此操作。 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.最简单的方法(但对于大型列表来说很慢)是使用像List这样的可调整大小的容器并在选择元素后删除它。 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.它会更快,因为从List的末尾删除通常比从中间删除要快得多。 As for shuffling, you can take a look at this question for more details.至于改组,您可以查看this question了解更多详细信息。

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) ] ;

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.与基于RemoveAt的实现的 O(n^2) 相比,这具有 O(n) 的优势。 Of course this doesn't matter much for short arrays.当然,这对于简短的 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?检查 Jon Skeet 对以下问题的回答,了解 shuffle 的良好(所有订单都同样可能)实现: Is using Random and OrderBy a good shuffle algorithm?

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.最好的办法就是创建一个重复列表,然后当你随机挑选一个字符串时,你可以将它从重复列表中删除,这样你就不能选择两次了。

The logic you could use is as follows:您可以使用的逻辑如下:

1) Pick a random integer over the range equal to the length of your array. 1)在等于数组长度的范围内选择一个随机 integer 。 You can do this using the System.Random class.您可以使用 System.Random class 来执行此操作。

2) Use the string corresponding to that array index 2)使用与该数组索引对应的字符串

3) Delete the item with that index from the array (may be easier with a list) 3)从数组中删除具有该索引的项目(使用列表可能更容易)

Then you can pick again and the same string won't appear.然后您可以再次选择,并且不会出现相同的字符串。 The array will be one element shorter.数组将短一个元素。

//SET LOWERLIMIT
cmd = new SqlCommand("select min(sysid) as lowerlimit from users", cs);
int _lowerlimit = (int) cmd.ExecuteScalar();
lowerlimit = _lowerlimit;

//SET UPPERLIMIT
cmd = new SqlCommand("select max(sysid) as upperlimit from users", cs);
int _upperlimit = (int) cmd.ExecuteScalar();
upperlimit = _upperlimit;

//GENERATE RANDOM NUMBER FROM LOWERLIMIT TO UPPERLIMIT
Random rnd = new Random();
int randomNumber = rnd.Next(lowerlimit, upperlimit+1);

//DISPLAY OUTPUT
txt_output.Text += randomNumber;

Use the below utility method使用以下实用程序方法

public static class ListExtensions
{
    public static T PickRandom<T>(this List<T> enumerable)
    {
        int index = new Random().Next(0, enumerable.Count());
        return enumerable[index];
    }
}

Then call the below way然后调用以下方式

string[] fruitsArray = { "apple", "orange"};
string inputString = fruitsArray.ToList().PickRandom();

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.您需要跟踪您使用过的那些,如果您不想/不能修改原始数组,最好在List中。 Use a while loop to check that it hasn't been used, and then add it to the "used" list.使用while循环检查它是否未被使用,然后将其添加到“已使用”列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM