2016-11-26 7 views
0

私は文字列のリストを持っています。このリストからランダムに選択したいと思います。文字列を選択するときは、リストからを削除してにする必要があります。すべての文字列が選択されたときにのみ、リストはに再集計されますです。これをどのように達成するのですか?置換えのないリストからランダムな文字列を取り出すC#

+0

リストをシャッフルし、文字列を1つずつ使用します。 –

答えて

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

をし、それを使用します。

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

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必要あなたは次の方法で使用すべきです:

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()); 
      } 
関連する問題