How to pick a random string from a list of strings?

Asked

Viewed 3,113 times

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 doesn’t have to be with an array, it can be with a list or something else that gets faster.

2 answers

6


If the collection where strings are accessible by 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’s an operation you want to use multiple times you can always define a extension method extracting 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: Regarding speed, since access is done by Dice the complexity is O(1).

4

Implementation of the Fisher-Yates shuffle algorithm:

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

I posted only as an alternative, in case you need more names, because it would be too much to use the solution to a single name. If the idea is to draw only one name, obviously the solution of the @Omni 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 result in IDEONE: http://ideone.com/FYbpDP

Implementation adapted from http://www.dotnetperls.com/fisher-yates-shuffle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.