How to randomise an array with certain criterion fulfilled?

Viewed 82

I have an array of elements. I want to randomise the position of the elements but I want certain criterion to be fulfilled in the output of the randomized array.

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

What I have done so far is used a function to randomize the order of the array. However, I don't know how to include these criteria into the function. Here is the function that I am using:

function shuffle(array) {
    var len = array.length, temp; // While there are elements in the array
    while (ctr > 0) {
        index = Math.floor(Math.random() * len); // Pick a random index
        ctr--; // Decrease ctr by 1
        temp = array[len]; // And swap the last element with it
        array[len] = array[index];
        array[index] = temp;
    }
    return array;
};

I want this array to be randomized but also that the 2s in the array should not come consecutively after the randomization. I want the output to be somewhat like this.

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

Any help in this respect would be appreciated. Thank you.

2 Answers

One possible idea:

Assuming you want three 2s, start with 2 1 2 1 2. Until the desired length is reached, insert an 1 into 4 possible positions _ 2 1 _ 2 1 _ 2 _, selected at random.

I would suggest to use Keith' approach

I would simply chunk the inputs first, basically get all 2's and add one of the 1's to the end of these chunks, randomise all the chunks, eg. [[2,1], [2,1], [2,1], [1], [1], [1], [1]], If you randomise this, and then flatten you won't get two 2's next to each other.

with a small change:

  1. Take a all wanted pairs with the spaced items 2 and non spaced items 1, take the non spaced items and an extra spaced item.

    [
        [2, 1], [2, 1], [2, 1], [1], [1], [1], [1], [1]
    ]
    
  2. Shuffle array.

  3. Flat array.

  4. Decrement length by one to delete the added space item and to enable to get the non spaced item as the last element.

Related