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
You can do something like this:
counts.v in the shuffled array, write v into the output array counts[v] times.var rng = new Random();
arr = arr
.GroupBy(i => i)
.OrderBy(g => rnd.Next())
.SelectMany(g => g)
.ToArray();
rnd (please edit your code to show this)? Please provide more details about how your answer works. I agree that this is likely the neatest way to solve this problem (although not using the shuffling algorithm OP asked for), but OP/future readers may require a little more of an explanation.g => rnd.Next() function is guaranteed to be called only once per group element. While this is true (at least in .NET 5), this solution is relying on undocumented behavior.x < y when called once and x > y when called a second time). Some sorting algorithms may throw errors or go into infinite loops when given inconsistent comparison functions. ericlippert.com/2011/01/31/bad-comparisons-part-four
{1, 1, 2, 2, 1, 1, 2, 2}? If so, is{2, 2, 1, 1, 2, 2, 1, 1}a valid output? Or are{1, 1, 1, 1, 2, 2, 2, 2}and{2, 2, 2, 2, 1, 1, 1, 1}the only valid outputs?