0

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()?

I want to rearrange the array to make the buttons in it appear in a different order everytime i output the array. I also dont want any of the buttons appear twice by accident, which means that i need ALL of the buttons to be output in a "random" order.

Update: I just found this test of array shufflings, there are interesting results.

Community
  • 1
  • 1
00Gheist00
  • 145
  • 8
  • 3
    What do you mean by doubles? What are you trying to achieve? – doldt May 08 '15 at 07:10
  • well sort() is not really randomizing in a proper way, i admit its short an clean but if you check the random percentage on certain keys you weill see that its not all that random. – 00Gheist00 May 08 '15 at 07:10
  • @doldt i am trying to rearrange the order of the buttons in the array without accidentally having one button be in there twice. The buttons are answers in a game so if they are always in the same spot the user has an easy win. – 00Gheist00 May 08 '15 at 07:12
  • @tomalak from the post i referred to: [0]): 1 = 29.19%, 2 = 29.53%, 3 = 20.06%, 4 = 11.91%, 5 = 5.99%, 6 = 3.32% – 00Gheist00 May 08 '15 at 07:19
  • @tomalak Using `.sort` to shuffle (atleast with your approach) does not yield great randomness... http://bost.ocks.org/mike/shuffle/compare.html – Jonathan May 08 '15 at 07:25
  • @rouby Already removed my comments. – Tomalak May 08 '15 at 07:26

0 Answers0