简体   繁体   中英

How can I randomly fill an array with 3 different strings?

I know how to randomly fill an array with integers.

But say I have Apple , Banana and Orange .
I want to fill an array with these 3 fruits in a random order.
How would I do this? Should I use Fisher-Yates Shuffle for this?

My array has to be written like this:

string[] basket = new string[20];

Create an IEnumerable in the desired size and then for each item select a random index from your strings array

var desiredArrayLength = 20; // Should be const or from config

var strings = new[] { "Apple", "Banana", "Orange" };
Random random = new Random();

var basket = Enumerable.Range(1, desiredArrayLength)
                       .Select(i => strings[random.Next(strings.Length)]).ToArray();

Make sure that no matter how you decide to initialize basket do not do something like new string[20] - use a const/config value so it won't be a magic number

More about magic numbers: What is a magic number, and why is it bad?

If you add all your string in a list you can then loop and select randomly one value and add it to your array

List<string> list = new List<string>();

list.Add("Apple");
list.Add("Banana");
list.Add("Orange");

string[] basket = new string[20];

Random rd = new Random();

for(int i = 0; i < basket.Length; i++)
{
    int randomValue = rd.Next(list.Count);

    basket[i] = list[randomValue];
}

Build an extension to repeat and shuffle any collection (this one uses Fisher-Yates)

public static class EnumerableExtensions
{
    private static readonly Random _rng = new Random();

    public static IEnumerable<T> Shuffle<T>( this IEnumerable<T> collection, Random rng = null )
    {
        rng = rng ?? _rng;

        var list = collection.ToList();
        for (int i = 0; i < list.Count; i++)
        {
            var j = i + rng.Next( list.Count - i );
            yield return list[j];
            if (i != j)
            {
                list[j] = list[i];
            }
        }
    }

    public static IEnumerable<T> Repeat<T>(this IEnumerable<T> collection, int count)
    {
        for ( int i = 0; i < count; i++ )
        {
            foreach ( var item in collection )
            {
                yield return item;
            }
        }
    }

}

and use it like

string[] fruits = new string[] { "Apple", "Banana", "Orange" };
string[] basket = fruits
    .Repeat( ( 20 + fruits.Length - 1 ) / fruits.Length )
    .Shuffle()
    .Take( 20 )
    .ToArray();

More random can be achieved by

public static class EnumerableExtensions
{
    ...

    public static IEnumerable<T> RandomRepeat<T>(this IEnumerable<T> collection, int count, Random rng = null)
    {
        rng = rng ?? _rng;
        var list = collection.ToList();
        for ( int i = 0; i < count; i++ )
        {
            var j = rng.Next( list.Count );
            yield return list[j];
        }
    }
}

and

string[] fruits = new string[] { "Apple", "Banana", "Orange" };
string[] basket = fruits.RandomRepeat( 20 ).ToArray();

So, I am at school right now, so I can't test the code myself but if I'm right the code could go something like this.

int Strings = 3;
string[] a1 = new[] {
  "Apple",
  "Banana",
  "Orange",
}

Random r1 = new Random();

string b1 = a1[r1.Next(0, a1.Length)];
listBox1.Items.Add(b1);

string b2 = a1[r1.Next(0, a1.Length)];
if (listBox1.Items.Contains(b2))
{
  b2 = a1[r1.Next(0, a1.Length)];
  listBox1.Items.Add(b2);
}
else
{
  listBox1.Items.Add(b2);
}
string b3 = a1[r1.Next(0, a1.Length)];
if (listBox1.Items.Contains(b3))
{
  b3 = a1[r1.Next(0, a1.Length)];
  listBox1.Items.Add(b3);
}
else
{
  listBox1.Items.Add(b3);
}

Here's also a C# class that can help you. https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx

It also checks whether the string is in the listbox and reroutes it, so it gets a different one your gonna want to make a check that continues it when it happens to be the same string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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