God of all wars
God of all wars

Reputation: 80

How to randomize an array, leaving the items that are the same far from each other?

Basically I have an array where there are similar items close by, but I would like to find a way where I leave these items that are the same apart from each other ex:

var array = [1,2,3,3,4]; 

var myWishArray = [1,2,3,4,3];
||
var myWishArray = [3,2,3,4,1];
||
var myWishArray = [3,2,3,1,4];
...

Upvotes: 1

Views: 45

Answers (1)

fafl
fafl

Reputation: 7385

If it's enough that two equal numbers are never neighbors, then you can

  • sort the list
  • fill a new array with these numbers in two passes, leaving a space of one

a = [1, 1, 1, 1, 2, 3, 2, 3, 4, 4, 4];
a.sort();
b = Array(a.length);
for (i = 0; i < a.length; i ++) {
    if (i * 2 < a.length) {
        b[i * 2] = a[i];
    } else {
        start = i - Math.ceil(a.length / 2)
        b[start * 2 + 1] = a[i];
    }
}
console.log(b);

Upvotes: 1

Related Questions