0

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
  • 1
    Do you have to handle arrays such as {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? Commented Jul 6, 2021 at 2:46
  • Only 1,1,1,1,2,2,2,2 and 2,2,2,2,1,1,1,1 Commented Jul 6, 2021 at 2:48

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

Comments

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

7 Comments

What is 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.
This works only if the 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.
In general when using LINQ you should not rely on how many calls will be made to your lambda functions, or which arguments they will be called with, or in what order the calls will be made. See this: github.com/dotnet/runtime/issues/31554
@JosephDaSilva Why does it only work if it's only guaranteed to be called once per group element? What issues do you see if it's called more than once?
@Llama If the key selector is called more than once and returns a different random value each time then you have an inconsistent comparison function (for example, it may report 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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.