I want to shuffle two lists, such that they are shuffled in the same way (provided that I have a method Shuffle(List list) that shuffles one list.
List<ObjX> listA = new List<ObjX>() { A, B, C, D };
List<ObjX> listB = new List<ObjX>() { W, X, Y, Z };
ShuffleTwoLists(listA , listB )
Result:
A: C, B, D, A
B: Y, X, Z, W
Is there a quick way to implement ShuffleTwoLists(listA , listB) in C#?
Option 1: zip, shuffle, unzip
To expand on Marcelo’s comment, and assuming you don’t mind creating new lists instead of shuffling the existing ones:
Option 2: shuffle the indexes
To expand on MAK’s answer with code:
Of course both approaches could mutate the original lists, with a bit more work.
Option 3: shuffle both lists with the same random seed
I personally like to pass a
Random(or whatever) into methods/classes which need them instead of creating new ones. So I’d give myShuffleaRandomparameter. It avoids various problems, and expresses the dependency nicely. You can use this to your advantage, by creating twoRandominstances with the same seed:Assuming
Shuffledoes the same thing when given the same sequence of random numbers, this will shuffle both lists in the same way.