Maria Jane Maria Jane - 2 months ago 6
Javascript Question

avoid same value to appear again using math.random()

animations = ['fadeIn','fadeInDown','slideInUp','flipInY','bounceInLeft'];


Imagine I generate random effect whenever user click something, so to achieve best experience, I would want the user to have same effect. But with

animations[ Math.floor(Math.random() * animations.length) -1];


that would happens.

How to avoid same value to appear again?

Answer

Two ways that i can suggest.

  1. First shuffle the array and go one by one from index 0 to 5 and then loop as much as you like.
  2. Pick a random element and slice it out up until the array is empty and then refresh your array from a back up. (be careful not to back up with a reference or your backup array gets deleted along with the one gets spliced. so use .slice())

Array.prototype.shuffle = function(){
  var a = this.slice(), // don't morph the original
      i = a.length,
      j;
  while (i > 1) {
    j = ~~(Math.random()*i--);
    a[i] = [a[j],a[j]=a[i]][0];
  }
return a;
};

var album = ["photo1","photo2","photo3","photo4","photo5"];
photos = album.shuffle();
photos.forEach(p => console.log(p));

console.log("another way") // the splice way

photos = album.slice();
while (photos.length) console.log(photos.splice(Math.floor(Math.random() * photos.length),1)[0]);
!photos.length && (photos = album.slice()); // restore photos album and continue
while (photos.length) console.log(photos.splice(Math.floor(Math.random() * photos.length),1)[0]);
!photos.length && (photos = album.slice()); // restore photos album and continue

Comments