带种子的Javascript随机排序 [英] Javascript random ordering with seed

查看:97
本文介绍了带种子的Javascript随机排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想随机排列4个项目的列表,但是要加上种子,以便只要您拥有相同的种子,您就可以得到相同顺序的项目.

I want to randomly shuffle a list of 4 items but with a seed so that so long as you have the same seed the you will get the same order of items.

["a", "b", "c", "d"]

我认为我可以使用Math.random获得种子,我不需要非常精确的东西.如何根据种子排序?

I figure I can get the seed with Math.random, I don't need something very exact. How do I sort according to the seed?

推荐答案

jsFiddle Demo

jsFiddle Demo

据我所知,您将需要为数组中的每个值播种随机值.在这方面,您可能想要执行以下操作:

You would need to seed a random value for each value in the array as far as I can tell. In that regards, you would probably want to do something like this:

for( var i = 0; i < length; i++ ){
    seed.push(Math.random());
}

要确保length与种子所用的长度相同.对于您的简单示例,该值为4.完成此操作后,您可以将种子传递给您的shuffle(或sort)函数,以确保获得相同的结果.洗牌也需要在循环中使用

Where you are insuring that length is the same length that the seed is for. This would be 4 for your simple example. Once that was done, you could pass the seed into your shuffle (or sort) function to ensure that the same results were obtained. The shuffle would need to use it in a loop as well

    var randomIndex = parseInt(seed[i] * (len - i));

所以这就是全部内容

种子函数,它将存储种子数组

var seeder = function(){
 var seed = [];
 return {
  set:function(length){
    for( var i = 0; i < length; i++ ){
        seed.push(Math.random());
    }
    return seed;
  },
  get: function(){
   return seed;
  },
  clear: function(){
   seed = []; 
  }
 };
}

基本的随机播放

function randomShuffle(ar,seed){
var numbers = [];
for( var a = 0, max = ar.length; a < max; a++){
    numbers.push(a);
}
var shuffled = [];
for( var i = 0, len = ar.length; i < len; i++ ){
    var r = parseInt(seed[i] * (len - i));
    shuffled.push(ar[numbers[r]]);
    numbers.splice(r,1);
}
return shuffled;
}

正在使用

var arr = ["a", "b", "c", "d"];
var seed = seeder();
seed.set(arr.length);
console.log(randomShuffle(arr,seed.get()));
console.log(randomShuffle(arr,seed.get()));
console.log(randomShuffle(arr,seed.get()));

这篇关于带种子的Javascript随机排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆