0

I am using shuffling methods from my previous question-

An extension method on IEnumerable needed for shuffling

But when I am using any of these methods for shuffling each elements of an IEnumerable<IEnumerable<T>> by calling something like-

SetOfSets.Select(set => set.Shuffle());

all the elements are shuffled in same order. How to make it random?

Community
  • 1
  • 1
Gulshan
  • 3,611
  • 5
  • 35
  • 46

1 Answers1

1

The problem is that the Shuffle extension method in the linked question instantiates a new Random object each time. Since the default constructor uses Environment.TickCount to seed the random number generator and this all happens very quickly, all the lists get the same random seed.

You need to instantiate a Random instance of your own and pass it to the Shuffle overload:

public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)

from this answer.

Your code, then, would be:

Random myRandom = new Random();
SetOfSets.Select(set => set.Shuffle(myRandom));
Community
  • 1
  • 1
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351