apple, mango, papaya, banana, guava, pineapple - How to generate these words randomly (one by one) using c# ? Please help me to generate the words randomly from the list of words I have..
Asked
Active
Viewed 1.2k times
4 Answers
5
Random rnd = new Random();
string GetRandomFruit()
{
string[] fruits = new string[] { "apple", "mango", "papaya", "banana", "guava", "pineapple" };
return fruits[rnd.Next(0,fruits.Length)];
}

L.B
- 114,136
- 19
- 178
- 224
-
Am I right in thinking that Sasi wanted a permutation algorithm, rather than a random selection with replacement? – Phillip Ngan Sep 05 '12 at 10:39
-
2@Phillip IMO could be interpreted either way - OP isn't clear. – StuartLC Sep 05 '12 at 10:42
4
You can get "random sorting" with LINQ's OrderBy
method and using 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);
}
The following foreach
will give you each item once from the words
array in a random order.

nemesv
- 138,284
- 16
- 416
- 359
3
you can write the following code.
string[] fruits = new string[] { "apple", "mango", "papaya", "banana", "guava", "pineapple" };
Console.WriteLine(fruits[new Random().Next(0, fruits.Length)]);

Nitin Vijay
- 1,414
- 12
- 28
-
Have you tried this? Creating a new `Random()` could seed with the same seed and result in the same output. – StuartLC Sep 05 '12 at 10:46
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

spender
- 117,338
- 33
- 229
- 351