How do I get a random string from a list of strings?

7

Code:

nomes = new string[5];        

nomes[0] = "José";
nomes[1] = "Carlos";
nomes[2] = "João";
nomes[3] = "Miriam";
nomes[4] = "Estela";

I put an array, but it does not have to be array, it can be with list or something else that gets faster.

    
asked by anonymous 30.05.2014 / 15:46

2 answers

6

If the collection where the strings are is accessible by index you can always do:

var rand = new Random();
// Caso seja um array
var nextRandString = rand.Next(0, tamanhoArray -1);
// Caso seja uma lista
var nextRandString = rand.Next(0, lista.Count - 1);

And use the random value to choose the string:

var arrayString = new string[5];
var randString = arrayString[nextRandString];

var listString = new List<string>();
var randString = listString[nextRandString];

If it is an operation that you want to use multiple times you can always set a extension method that extracts the random element (in this example defined for any type of element):

private static readonly Random _rand = new Random();

public static T GetRandomString<T>(this ICollection<T> source)
{
    var randIndice = _rand.Next(0, source.Count - 1);
    return source.ElementAt(randIndice);
}

Edit: For speed, since access is done by index complexity is O (1).

    
30.05.2014 / 15:50
3

Implementation of Fisher-Yates Scrambling Algorithm:

This solution implements the Fisher-Yates algorithm in the Shuffle<T>(T[] array) function, which shuffles the order of the items, so you can get the amount of results you need, in sequence.

I only put it as an alternative if you need more names, because it would be an exaggeration to use the solution for one name only. If the idea is to just sort out a name, obviously the @Omni solution is more appropriate.

using System;
public class Sorteio
{
   // Esta é a função de embaralhamento que você deve implementar no seu código:
   static Random _random = new Random();

   public static void Shuffle<T>(T[] array)
   {
      var random = _random;
      for (int i = array.Length; i > 1; i--)
      {
         int j = random.Next(i);
         T tmp = array[j];
         array[j] = array[i - 1];
         array[i - 1] = tmp;
      }
   }
   // Teste do algoritmo:
   public static void Main()
   {
      string[] array = {
         "José",
         "Carlos",
         "João",
         "Miriam",
         "Estela"
      };
      // Embaralhamos a lista...
      Shuffle(array);
      foreach (string value in array)
      {
         Console.WriteLine(value);
      }      
   }
}
  

See the IDEONE result: link

Tailored implementation of link

    
31.05.2014 / 17:25