问题描述
限时送ChatGPT账号..我有一个
List<string> notizen = new List<string>();
我想从中随机选择一个条目,但在显示通知的所有条目之前不应重复此条目.
I want to choose a random entry from it but this entry should not be repeated until all entries of notizen have been shown.
应用程序如下所示:
字符串在屏幕上,您点击它,屏幕上就会出现另一个文本.我想随机浏览通知列表,不要重复输入,直到显示所有条目,然后从一个新的随机版本的通知开始.
String is on the screen, you tap on it, another text is on the screen. I want to randomly go through the notizen list without having double entries until all entries have been shown, then it starts with a new randomized version of notizen.
notizen 本身可以随机化,不需要临时列表.但我发现 LINQ 在 monodroid 中不存在.
notizen could be randomized itself, no temporary list necessary. But I found LINQ to not exist in monodroid.
推荐答案
您可以使用 O(n) 中的nofollow">Fisher-Yates 算法;一旦您的迭代器等于 n,则执行第二次 shuffle,依此类推.
You can shuffle your List using Fisher–Yates algorithm in O(n)
; once your iterator equals n, perform a second shuffle and so on.
它的伪代码,如维基百科所示,是:
The pseudocode for it, as presented in wikipedia, is :
To shuffle an array a of n elements (indices 0..n-1):
for i from n − 1 downto 1 do
j ← random integer with 0 ≤ j ≤ i
exchange a[j] and a[i]
您甚至可以为此编写扩展方法,例如:
You could even write an extension method for that, something like :
public static Random rand = new Random();
public static List<T> Shuffle<T>(this List<T> original)
{
List<T> lst = new List<T>(original);
for (int i = lst.Count - 1; i >= 1; i--)
{
int j = rand.Next(0, i + 1);
T tmp = lst[j];
lst[j] = lst[i];
lst[i] = tmp;
}
return lst;
}
以便您可以使用
var shuffled = notizen.Shuffle();
这篇关于随机化列表<string>没有重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论