How to shuffle an array with duplicate items, but duplicates can't be back to back

Viewed 142

Given an array [1, 2, 2, 3, 4, 4, 5], is it possible to shuffle the array while preventing the duplicates to be next to each other?

For example:

  • [1, 2, 3, 4, 2, 5, 4] is an acceptable solution.
  • [1, 2, 3, 4, 4, 2, 5] is not an acceptable solution since 4 is next to another 4

This seems like a simple question but after thinking about it, the solution seems complicated. Any help is greatly appreciated, thanks!!

1 Answers

If you don't care about the execution time of the algorithm, just shuffle a few times until you get the result you want

let arr = [1, 2, 2, 3, 4, 4, 5];

const hasDublicateItems = (arr) => arr.some((v, i, a) => v === a[i+1]);

while (hasDublicateItems(arr)) 
  arr = arr.sort(() => (Math.random() > .5) ? 1 : -1);

console.log(arr);
.as-console-wrapper{min-height: 100%!important; top: 0}

Related