jeudi 18 juin 2015

Generation of new random items from a List

I have a code that generates a new random item from a ist without repetition.

   class text_generator
     {
       public int getWordIndex(List<string> source, Random value)
        {
          return value.Next(0, source.Count - 1);
        }
          public bool checkListLength(List<string> source)
        {
          return source.Count == 0;
        }
       public string getText(List<string> source, List<string>                backup_source, Random value)
        {
          if (checkListLength(source))
          {
            source.AddRange(backup_source);
          }
          ;
          int index = getWordIndex(source, value);
          string result = source[index];
          source.RemoveAt(index);
          return result;
      }
  }

Then I open a main list and an empty list.

text_generator textix = new text_generator();
List<string> hi = new List<string> { "Hi", "Howdy", "Hey" //etc };
List<string> work_hi = new List<string>();

And... Generate. They will always be different until all elements will be used.

Random rand = new Random();
Console.WriteLine(textix.getText(work_hi, hi, rand));

My question is: While this code works fine, it seems a bit long. Is it possible to make the same with just one method? Is it possible NOT to open one more list? How can I do it?




Aucun commentaire:

Enregistrer un commentaire