suryanaga
suryanaga

Reputation: 4002

don't repeat any items from math.random

I'm using this to get a random item from my array (and append it to each list item)

   $('li').each(function(){
       var items = Array('the','and','to','a');
       var item = items[Math.floor(Math.random()*items.length)];
       $(this).append(item);
    });

I'm sure this is a quick thing but I don't really know where to look. How can I make sure there are no repeating items?

Upvotes: 1

Views: 1797

Answers (3)

Tamás Zahola
Tamás Zahola

Reputation: 9321

So you want the elements randomized but not repeating? Then what you're looking for is a random permutation. If you want a quick'n'dirty solution, just randomly swap elements in your array. If you want a uniformly distributed random permutation, have a look at Eric Lippert's articles on the subject: http://ericlippert.com/2013/05/02/producing-permutations-part-six/

Upvotes: 0

ReDEyeS
ReDEyeS

Reputation: 851

Working Demo Here

you need to remove the used value from the array.

  var items = Array('the', 'and', 'to', 'a');
  $('li').each(function () {
      var randomNum = Math.floor(Math.random() * items.length)
      var item = items[randomNum];
      $(this).append(item);
      items.splice(randomNum, 1);
      
  });

Se your Demo on JsFiddle

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

Try

var items = new Array('the','and','to','a');
$('li').each(function(){
    var item = items.splice(Math.floor(Math.random() * items.length), 1);
    $(this).append(item);
});

Demo: Fiddle

Upvotes: 1

Related Questions