How to shuffle an array while grouping equal values together?

146 Views Asked by At

Let say I have an array like this.

int[] arr = {1,2,3,4,4,5,6,7,8,8,8,1};

How do I shuffle it, but have all equal values beside each other?

Sample expected output after shuffle:

3,1,1,8,8,8,7,2,4,4,6,5
2

There are 2 best solutions below

7
On
var rng = new Random();    
arr = arr
    .GroupBy(i => i)
    .OrderBy(g => rnd.Next())
    .SelectMany(g => g)
    .ToArray();
0
On

You can do something like this:

  • Find the unique values in the array and the number of times each one occurs. Store the counts in a dictionary, say counts.
  • Shuffle the unique values using a shuffling algorithm such as Fisher-Yates.
  • For each value v in the shuffled array, write v into the output array counts[v] times.