mardi 4 janvier 2022

Randomize several arrays with one general function, without repeating values [duplicate]

I have multiple different arrays in Javascript of which I want random outputs. I did not want to write numerous functions for every array, therefor I am using this general function:

function randomValue() {
    return this[~~(Math.random()*this.length)];
}

var data = [ … ];
var moreData = [ … ];

data.random=randomValue;
moreData.random=randomValue;

However this function runs the risk of successively repeating values. I tried to combat this by trying:

function randomValue() {
    let random;
    while((random=this[~~(Math.random()*this.length)]) == this.previous);
    this.previous=random;
    return random;
}

But this does not solve the problem.

Any ideas?




Aucun commentaire:

Enregistrer un commentaire