2016-11-26 97 views
0

我有一個字符串列表,我想隨機從這個列表中選擇。當選擇一個字符串時,必須從列表中刪除。只有當所有的字符串被挑選出來後,列表中的纔會重新填充。我如何實現這一目標?從沒有替換的列表中選擇一個隨機字符串C#

+0

隨機播放列表,然後逐個使用字符串。 –

回答

0

首先,製作一個隨機數發生器。

Random rand = new Random(); 

然後,生成一個數字並從列表中刪除該項目。我假設你正在使用System.Collections.Generic.List

int num = Random.Next(list.Count); 
list.RemoveAt(num); 
0

可以實現它非常簡單:

public static partial class EnumerableExtensions { 
    public static IEnumerable<T> RandomItemNoReplacement<T>(this IEnumerable<T> source, 
     Random random) { 

     if (null == source) 
     throw new ArgumentNullException("source"); 
     else if (null == random) 
     throw new ArgumentNullException("random"); 

     List<T> buffer = new List<T>(source); 

     if (buffer.Count <= 0) 
     throw new ArgumentOutOfRangeException("source"); 

     List<T> urn = new List<T>(buffer.Count); 

     while (true) { 
     urn.AddRange(buffer); 

     while (urn.Any()) { 
      int index = random.Next(urn.Count); 

      yield return urn[index]; 

      urn.RemoveAt(index); 
     } 
     } 
    } 
    } 

,然後使用它:

private static Random gen = new Random();  

... 

var result = new List<string>() {"A", "B", "C", "D"} 
    .RandomItemNoReplacement(gen) 
    .Take(10); 

// D, C, B, A, C, A, B, D, A, C (seed == 123) 
Console.Write(string.Join(", ", result)); 
0

我想,你需要somethink喜歡隔壁班:

public class RandomlyPickedWord 
    { 
     public IList<string> SourceWords{ get; set; } 

     protected IList<string> Words{ get; set; } 

     public RandomlyPickedWord(IList<string> sourceWords) 
     { 
      SourceWords = sourceWords; 
     } 

     protected IList<string> RepopulateWords(IList<string> sources) 
     { 
      Random randomizer = new Random(); 
      IList<string> returnedValue; 
      returnedValue = new List<string>(); 

      for (int i = 0; i != sources.Count; i++) 
      { 
       returnedValue.Add (sources [randomizer.Next (sources.Count - 1)]); 
      } 

      return returnedValue; 
     } 

     public string GetPickedWord() 
     { 
      Random randomizer = new Random(); 
      int curIndex; 
      string returnedValue; 

      if ((Words == null) || (Words.Any() == false)) 
      { 
       Words = RepopulateWords (SourceWords); 
      } 

      curIndex = randomizer.Next (Words.Count); 
      returnedValue = Words [curIndex]; 
      Words.RemoveAt (curIndex); 

      return returnedValue; 
     } 
    } 

你應該用下一個方法:

IList<string> source = new List<string>(); 
      source.Add ("aaa"); 
      source.Add ("bbb"); 
      source.Add ("ccc"); 
      RandomlyPickedWord rndPickedWord = new RandomlyPickedWord (source); 

      for (int i = 0; i != 6; i++) 
      { 
       Console.WriteLine (rndPickedWord.GetPickedWord()); 
      } 
相關問題