随机化列表<string>没有重复

编程入门 行业动态 更新时间:2024-10-18 14:22:27
本文介绍了随机化列表<string>没有重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-24 17:47:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1068486.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   随机化   lt   string   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!