Pick Random String From Array

2019-01-11 01:22发布

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.

8条回答
2楼-- · 2019-01-11 01:29

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.

查看更多
来,给爷笑一个
3楼-- · 2019-01-11 01:32

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?

查看更多
狗以群分
4楼-- · 2019-01-11 01:33
//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;
查看更多
三岁会撩人
5楼-- · 2019-01-11 01:36

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();
查看更多
神经病院院长
6楼-- · 2019-01-11 01:38

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 a while loop to check that it hasn't been used, and then add it to the "used" list.

查看更多
一纸荒年 Trace。
7楼-- · 2019-01-11 01:39

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.

查看更多
登录 后发表回答