-6

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..

0

4 Answers 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)];
}
2
  • Am I right in thinking that Sasi wanted a permutation algorithm, rather than a random selection with replacement? Commented Sep 5, 2012 at 10:39
  • 2
    @Phillip IMO could be interpreted either way - OP isn't clear.
    – StuartLC
    Commented Sep 5, 2012 at 10:42
4

You can get "random sorting" with LINQ's OrderBy method and using Guids

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.

1
  • I like your solution! Except Sasi indicated C#-2 in the tags. Commented Sep 5, 2012 at 10:44
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)]);
1
  • Have you tried this? Creating a new Random() could seed with the same seed and result in the same output.
    – StuartLC
    Commented Sep 5, 2012 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.