jeudi 21 septembre 2017

Part random retrieval, part minimize repeats

I have an array of 10 numbers:

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

I've written a function (below) to return a random element from the array without repeating a return of the same element until 8 other elements have been returned. It works but seems very inefficient because the random number generator will often need to be invoked many times before the code can continue. Is there a more efficient way to accomplish the same result?

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var recentlyReturned = [];

function minimalRepeat() {

var i = Math.floor(Math.random() * 10);
while( recentlyReturned.indexOf(i) != -1 ) {
    i = Math.floor(Math.random() * 10);
}

recentlyReturned.push(i);
while(recentlyReturned.length>8) {
    recentlyReturned.shift();
}
return array[i];
}


for(var i=1; i<20; i++) {
    console.log(minimalRepeat());
}




Aucun commentaire:

Enregistrer un commentaire