I need to shuffle an array of objects that I receive from an API. The array will have the same occurrence of repeated objects.
Valid input:
- ["a","a","a","a","b","b","b","b","c","c","c","c"]
- ["a", "a", "b", "b"] or ["b", "b", "a", "a"]
Invalid input:
- ["a","a","a","a","b","c"]
- ["a", "b", "a", "b"]
After shuffling:
- The objects at i and i + 1 should be different
- Every time the array is shuffled it should generate a new valid solution
Valid outputs:
- b,a,c,b,a,c,a,c,b,a,c,b
- c,a,b,a,b,c,a,c,b,a,b,c
- c,b,a,c,b,a,c,b,a,c,b,a
Invalid outputs:
- c,c,a,b,b,a,c,b,a,c,b,a
I started using Fisher–Yates for an initial shuffle and then validate if the solution is valid. This brute force approach is working once I have a small set, but as the input grows it gets useless. Is there an efficient way to generate a random permutation without leaving duplicates next to each other?
Efficient algorithm for ordering different types of objects gave an insight on how to keep the objects of the same kind far from each other, unfortunately, I'll run into the same solution/pattern If I try to shuffle it again.
https://stackoverflow.com/a/32366585/4271233 generates all possible permutations that satisfy the "no two duplicates next to each other", but I'd sadly need to generate all of them and then pick randomly one