mercredi 14 décembre 2016

Is there better way to make semi-random order of array, based on string

I made a code to shuffle array in semi-random way,that is it has to be random based on string but for same string return same order. Below is my code

function djbHash(s) {
    let hash = 5381;

    for (let c of s) {
        hash = hash * 33 + c.charCodeAt(0);
    }
    return hash;
}

function mapToValues(s, values) {
    return values[djbHash(s) % values.length];
}


var randomArray=[];
var myArray = [0,1,2,3,4,5,6,7,8,9];
var string  = "bigcat";
var length = myArray.length;
for(var i=0;i<length;i++){
    console.log(myArray)
  var item = mapToValues(string, myArray);
    var removed = myArray.splice(myArray.indexOf(item),1);
  console.log(removed);
  randomArray.push(removed[0]);
}
console.log(randomArray);

jsFiddle

It works, i only have a question is there better way to do it?




Aucun commentaire:

Enregistrer un commentaire