vendredi 8 mai 2015

Reorganizing an array without sort() and doubles

I have an array like this named contents:

contents[0]='<button id=' + randomChar0 +' class="btn" onclick="check('+ f + randomChar0 + f +');">' + randomChar0 + '</Button>';
contents[1]='<button id=' + randomChar1 +' class="btn" onclick="check('+ f + randomChar1 + f +');">' + randomChar1 + '</Button>';
contents[2]='<button id=' + randomChar2 +' class="btn" onclick="check('+ f + randomChar2 + f +');">' + randomChar2 + '</Button>';

I have tried to rearrange it with this code:

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
};

calling it like this:

shuffle(contents);

from How to randomize (shuffle) a JavaScript array?

But this Method gives me doubles quite often.

Any idea how to make sure the buttons always change their order without any doubling and without using sort()?




Aucun commentaire:

Enregistrer un commentaire