I'm running a site where the user's only way of navigating the subdirectories is via random pages (akin to Wikipedia's Random Page feature). I already implemented a code to call up random pages and it works fine, but I want to minimize the chance of the same page being called up again after the onclick execution.
I stumbled over the Fisher-Yates-Knuth shuffle while researching a better method and tried to implement it into my script:
function Next() {
var links = [];
links[0] = "/arch/g1";
links[1] = "/arch/g2";
links[2] = "/arch/g3";
links[3] = "/arch/g4";
var m = links.length, t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = links[m];
links[m] = links[i];
links[i] = t;
}
window.location = links[m]
}
The script basically works, but it still results in calling up the same page twice or even three times in a row. I'm still pretty new at JS, so it'd be great if someone could point me in the right direction.
Eeach call on Next() function is shuffle array of links and get one index from array. You have 4 different links, on calling this function 3 times you have good chance to get same page.
Try this:
var links = ["/arch/g1","/arch/g2","/arch/g3","/arch/g4"];
function shuffle(links) {
var m = links.length, t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = links[m];
links[m] = links[i];
links[i] = t;
}
}
function Next(){
if(links.length === 0){
links = ["/arch/g1","/arch/g2","/arch/g3","/arch/g4"];
shuffle(links);
}
var nextUrl = links[links.length - 1];
links.splice(links.length - 1, 1);
window.location = nextUrl;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments