Javascript random ordering with seed

后端 未结 4 1845
故里飘歌
故里飘歌 2021-01-02 09:47

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\         


        
4条回答
  •  走了就别回头了
    2021-01-02 10:30

    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());
    }
    

    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));
    

    So here is what it all breaks down into

    The seed function which will store the array of seeds

    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 = []; 
      }
     };
    }
    

    A pretty basic shuffle

    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;
    }
    

    Being used

    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()));
    

提交回复
热议问题