[英]Picking a random string from a list with no replacement C#
我有一個字符串列表,我想從這個列表中隨機選擇。 選擇字符串后,必須將其從列表中刪除 。 僅當所有字符串都已選取后,列表才會重新填充 。 我該如何實現?
首先,制作一個隨機數生成器。
Random rand = new Random();
然后,生成一個數字並從列表中刪除該項目。 我假設您正在使用System.Collections.Generic.List
。
int num = Random.Next(list.Count);
list.RemoveAt(num);
您可以很簡單地實現它:
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));
我認為,您需要像下一堂課這樣的東西:
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 ());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.