'tag.htm'; break; case 'flag': $pre .= $default_pre .= 'flag.htm'; break; case 'my': $pre .= $default_pre .= 'my.htm'; break; case 'my_password': $pre .= $default_pre .= 'my_password.htm'; break; case 'my_bind': $pre .= $default_pre .= 'my_bind.htm'; break; case 'my_avatar': $pre .= $default_pre .= 'my_avatar.htm'; break; case 'home_article': $pre .= $default_pre .= 'home_article.htm'; break; case 'home_comment': $pre .= $default_pre .= 'home_comment.htm'; break; case 'user': $pre .= $default_pre .= 'user.htm'; break; case 'user_login': $pre .= $default_pre .= 'user_login.htm'; break; case 'user_create': $pre .= $default_pre .= 'user_create.htm'; break; case 'user_resetpw': $pre .= $default_pre .= 'user_resetpw.htm'; break; case 'user_resetpw_complete': $pre .= $default_pre .= 'user_resetpw_complete.htm'; break; case 'user_comment': $pre .= $default_pre .= 'user_comment.htm'; break; case 'single_page': $pre .= $default_pre .= 'single_page.htm'; break; case 'search': $pre .= $default_pre .= 'search.htm'; break; case 'operate_sticky': $pre .= $default_pre .= 'operate_sticky.htm'; break; case 'operate_close': $pre .= $default_pre .= 'operate_close.htm'; break; case 'operate_delete': $pre .= $default_pre .= 'operate_delete.htm'; break; case 'operate_move': $pre .= $default_pre .= 'operate_move.htm'; break; case '404': $pre .= $default_pre .= '404.htm'; break; case 'read_404': $pre .= $default_pre .= 'read_404.htm'; break; case 'list_404': $pre .= $default_pre .= 'list_404.htm'; break; default: $pre .= $default_pre .= theme_mode_pre(); break; } if ($config['theme']) { $conffile = APP_PATH . 'view/template/' . $config['theme'] . '/conf.json'; $json = is_file($conffile) ? xn_json_decode(file_get_contents($conffile)) : array(); } !empty($json['installed']) and $path_file = APP_PATH . 'view/template/' . $config['theme'] . '/htm/' . ($id ? $id . '_' : '') . $pre; (empty($path_file) || !is_file($path_file)) and $path_file = APP_PATH . 'view/template/' . $config['theme'] . '/htm/' . $pre; if (!empty($config['theme_child']) && is_array($config['theme_child'])) { foreach ($config['theme_child'] as $theme) { if (empty($theme) || is_array($theme)) continue; $path_file = APP_PATH . 'view/template/' . $theme . '/htm/' . ($id ? $id . '_' : '') . $pre; !is_file($path_file) and $path_file = APP_PATH . 'view/template/' . $theme . '/htm/' . $pre; } } !is_file($path_file) and $path_file = APP_PATH . ($dir ? 'plugin/' . $dir . '/view/htm/' : 'view/htm/') . $default_pre; return $path_file; } function theme_mode_pre($type = 0) { global $config; $mode = $config['setting']['website_mode']; $pre = ''; if (1 == $mode) { $pre .= 2 == $type ? 'portal_category.htm' : 'portal.htm'; } elseif (2 == $mode) { $pre .= 2 == $type ? 'flat_category.htm' : 'flat.htm'; } else { $pre .= 2 == $type ? 'index_category.htm' : 'index.htm'; } return $pre; } ?>javascript - getting random element from array returns same element - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览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. 暂无评论