如何用3个不同的字符串随机填充数组? [英] How can I randomly fill an array with 3 different strings?
本文介绍了如何用3个不同的字符串随机填充数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道如何用整数随机填充数组。
I know how to randomly fill an array with integers.
但是我有 Apple
,香蕉
和橙色
。
我想用随机顺序用这3种水果填充数组。
我该怎么做?我应该为此使用Fisher-Yates Shuffle吗?
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?
我的数组必须这样写:
string[] basket = new string[20];
推荐答案
如果将所有字符串添加到列表中,则可以然后循环并随机选择一个值并将其添加到数组中
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];
}
这篇关于如何用3个不同的字符串随机填充数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文