c# – Raffle where the name cannot be drawn more than once

Question:

I need to make a simple drawing software, but I don't know how to take the names that were entered in the list box and draw one among them. The same name cannot be drawn more than once. How to do this part?

Answer:

Fisher-Yates shuffling algorithm implementation:

A simple solution for your case would be to produce a scrambled copy of the list of names, so that you can remove them one by one.

This can be done with a very short and efficient function:

   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;
      }
   }

Characteristics:

  • It is of order O(n).

  • If you need to draw the entire list, it ends up being more efficient than drawing individual items one by one and controlling what has already been drawn,

  • This function is easily adaptable to other collections besides arrays.

Full code for testing:

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()
   {
      // Aqui você deve pegar os valores da sua lista:
      string[] array = { "Alaor", "Joseval", "Salustiano", "Gomide", "Castro" };
      // Embaralhamos a lista...
      Shuffle(array);
      // ... e, uma vez embaralhada a lista, não precisa sortear novamente.
      // basta ir pegando os resultados um por um, que os nomes não se repetirão:
      foreach (string value in array)
      {
         Console.WriteLine(value);
      }      
   }
}

See the result on IDEONE: http://ideone.com/aki905

Adapted implementation from http://www.dotnetperls.com/fisher-yates-shuffle

Scroll to Top