苹果、芒果、木瓜、香蕉、番石榴、菠萝 - 如何使用 c# 随机(一个接一个)生成这些单词?请帮我从我拥有的单词列表中随机生成单词..
问问题
10609 次
4 回答
5
Random rnd = new Random();
string GetRandomFruit()
{
string[] fruits = new string[] { "apple", "mango", "papaya", "banana", "guava", "pineapple" };
return fruits[rnd.Next(0,fruits.Length)];
}
于 2012-09-05T10:35:06.697 回答
3
You can use Fisher-Yates to do an in place shuffle of an array:
static class ArrayMethods
{
private static readonly Random rng = new Random();
public static void Shuffle<T>(IList<T> list)
{
var r = rng;
var len = list.Count;
for(var i = len-1; i >= 1; --i)
{
var j = r.Next(i);
var tmp = list[i];
list[i] = list[j];
list[j] = tmp;
}
}
}
as follows:
var arr = new[]{
"apple",
"mango",
"papaya",
"banana",
"guava",
"pineapple"
};
ArrayMethods.Shuffle(arr);
foreach(var item in arr)
//print 'em out
于 2012-09-05T10:51:52.120 回答
3
OrderBy
您可以使用 LINQ 的方法和使用Guid
s获得“随机排序”
var words = new [] {"apple", "mango", "papaya", "banana", "guava", "pineapple"};
var wordsInRandomOrder = words.OrderBy(i => Guid.NewGuid());
foreach(var word in wordsInRandomOrder)
{
Console.WriteLine(word);
}
以下foreach
将以随机顺序为您提供数组中的每个项目。words
于 2012-09-05T10:36:17.287 回答
3
您可以编写以下代码。
string[] fruits = new string[] { "apple", "mango", "papaya", "banana", "guava", "pineapple" };
Console.WriteLine(fruits[new Random().Next(0, fruits.Length)]);
于 2012-09-05T10:41:09.840 回答