Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

c# - Randomize List<string> without duplicates

I have a

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.

Application looks like this:

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 could be randomized itself, no temporary list necessary. But I found LINQ to not exist in monodroid.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

so that you could generate your shuffled list with

var shuffled = notizen.Shuffle();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...