最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - getting random element from array returns same element - Stack Overflow

programmeradmin5浏览0评论

Please refer below code.

for (var i = 0; i < elements.length; i++) 
{
     //var element = elements[Math.floor(Math.random()*elements.length)];
     this.animateSymbol(elements[Math.floor(Math.random()*elements.length)]);
}

elements array contains list of svg elements(circle/path/ellipse etc). I want to select the random element from elements array.

it's return the same element in some cases I want to select the element randomly no need to select the same element again. Need to select different element from that array.

What's the problem ? Why its returning same index and same element ?

Thanks,

Siva

Please refer below code.

for (var i = 0; i < elements.length; i++) 
{
     //var element = elements[Math.floor(Math.random()*elements.length)];
     this.animateSymbol(elements[Math.floor(Math.random()*elements.length)]);
}

elements array contains list of svg elements(circle/path/ellipse etc). I want to select the random element from elements array.

it's return the same element in some cases I want to select the element randomly no need to select the same element again. Need to select different element from that array.

What's the problem ? Why its returning same index and same element ?

Thanks,

Siva

Share Improve this question edited Jun 11, 2013 at 9:31 Rakesh Shetty 4,5788 gold badges42 silver badges81 bronze badges asked Jun 11, 2013 at 9:22 SivaRajiniSivaRajini 7,37522 gold badges84 silver badges129 bronze badges 2
  • 2 Nothing says the random number can't be the same as a previous random. – Kevin Bowersox Commented Jun 11, 2013 at 9:29
  • are you sure elements contains more than one element? Do a console.log(elements.length) . – Stefan Commented Jun 11, 2013 at 9:30
Add a ment  | 

5 Answers 5

Reset to default 8

Random numbers are random. There's no guarantee you won't get the same random number twice. In fact, when you convert the random numbers to a limited range of integers, it's quite likely you will get the same number twice.

You can fix this by copying the array and then each time you get a value from the array, remove it. Let's also break out the code that generates the random index as a separate function; it's handy in other situations too:

// Return a random integer >= 0 and < n
function randomInt( n ) {
    return Math.floor( Math.random() * n );
}

var copy = elements.slice();
while( copy.length ) {
    var index = randomInt( copy.length );
    this.animateSymbol( copy[index] );
    copy.splice( index, 1 );
}

And just for fun, here's another way you could code that loop:

var copy = elements.slice();
while( copy.length ) {
    var index = randomInt( copy.length );
    this.animateSymbol( copy.splice( index, 1 )[0] );
}

Either one does the same thing. I kind of like the step by step approach for clarity, but it can be quite handy that the .splice() method returns an array of the element(s) you delete.

Here's a version of the code you can paste into the JavaScript console to test:

// Return a random integer >= 0 and < n
function randomInt( n ) {
    return Math.floor( Math.random() * n );
}

var elements = [ 'a', 'b', 'c', 'd', 'e' ];
var copy = elements.slice();
while( copy.length ) {
    var index = randomInt( copy.length );
    console.log( copy.splice( index, 1 )[0] );
}
console.log( 'Done' );

It's also worth a look at Xotic750's answer. It uses the Fisher-Yates shuffle which randomizes an array in place. This would likely be more efficient for a very lengthy array.

So what you want is akin to a deck of cards, you shuffle them and take them one by one and therefore they are never repeated.

I would use something like the following for your problem, uses a standard Fisher-Yates shuffle.

function shuffle(obj) {
  var i = obj.length;
  var rnd, tmp;

  while (i) {
    rnd = Math.floor(Math.random() * i);
    i -= 1;
    tmp = obj[i];
    obj[i] = obj[rnd];
    obj[rnd] = tmp;
  }

  return obj;
}

var elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var randomised = elements.slice();
shuffle(randomised);

randomised.forEach(function(element) {
  console.log(element);
});

It is because you are using random there is no assurance that same number will not be repeated.

In your case I would suggest you to use some sort of shuffle to create a random order array.

You can find such method here

Try capturing the random numbers generated and checking that you are not using them over again.

Here is a quick object I created for this purpose:

function PersistentRandom(exclusiveUpperBounds){
  this.spent = [];
  this.bounds = exclusiveUpperBounds;
}

PersistentRandom.prototype.getValue = function(){
    if(this.spent.length != this.bounds -1){
        var tmp = Math.floor(Math.random()* this.bounds);
        if(this.spent.indexOf(tmp) == -1){
            this.spent.push(tmp);
            return tmp;
        }else{
            return this.getValue();
        }
    }else{
        //If all numbers are used reset and start again
        this.spent = [];
        return this.getValue();
    }
};

//Usage
var pr = new PersistentRandom(11);

var x = 0;
while(x < 15){
   console.log(pr.getValue());
   x++;
}

Working Example http://jsfiddle/zasdj/

So you want a random element each time? but never the same element twice?

try this:

for (var i = 0; i < elements.length; i++) {
     //var element = elements[Math.floor(Math.random()*elements.length)];
     var index = Math.floor(Math.random()*elements.length);         
     this.animateSymbol(elements[index]);   
     elements.splice(index, 1);
}

this will remove the item from array once it has been selected

发布评论

评论列表(0)

  1. 暂无评论