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.