我有一个字符串列表,我想随机从这个列表中选择。当选择一个字符串时,必须从列表中删除。只有当所有的字符串被挑选出来后,列表中的才会重新填充。我如何实现这一目标?从没有替换的列表中选择一个随机字符串C#
0
A
回答
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());
}
相关问题
- 1. 从列表中选择任意一个随机字符串
- 2. 如何从列表中选择一个随机字符串
- 3. 从字符串替换一些随机选择[]
- 4. 选择下拉列表在C#中的随机字符串
- 5. 用随机替换替换字符串的随机字
- 6. 从C#中的字符串列表生成随机字符串?
- 7. 使用随机从给定的字符串列表中选择一个程序
- 8. Bash从列表中选择随机字符串
- 9. 从给定列表中选择随机字符串
- 10. 如何在字符串中随机替换一个字符?
- 11. 从Android的strings.xml中随机选择一个字符串
- 12. 如何随机替换字符串列表中的
- 13. 如何从C#中的预写字符串中随机选择?
- 14. 从数组列表中随机打印一个没有重复的字符串
- 15. PHP从字符串中替换一个随机单词并替换为变量
- 16. 从JSON字符串中选择一个随机条目
- 17. 随机从JSON字符串中选择一个单词
- 18. 如何从数组中随机选择一个字符串
- 19. 用随机字符替换字符串中的每个数字
- 20. 从c#中按钮列表中选择一个随机变量#
- 21. 替换列表中的字符串C#
- 22. 如何从可用字符串中选择一个随机字符串
- 23. 如何生成随机数,字符串并从Watin中的下拉列表中选择随机选择?
- 24. 2从一个列表中随机选择 - C#
- 25. Python从字符串中有选择地替换字符
- 26. Python:列表和随机。如何从0到[列表中的字符串数量]之间选择随机数字?
- 27. 替换字符串列表中的一个字符串
- 28. 如何从列表中选择一个随机字符串并将其分配给一个变量C#
- 29. 如何随机选择三个字符串中的一个?
- 30. 替换时的统一随机选择
随机播放列表,然后逐个使用字符串。 –