HTML link array shuffling issues

I'm running a site where the custom way to navigate through subdirectories is through random pages (similar to the "Random Wikipedia Page" feature). I have already implemented the code to call random pages and it works great, but I want to minimize the chance of calling the same page again after doing onclick.

I came across a Fisher-Yates-Knuth shuffle while researching the best 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]
}

      

Basically the script works, but it still calls the same page two or three times in a row. I'm still pretty new to JS so it would be great if someone could point me in the right direction.

+3


source to share


1 answer


Eeach function call Next () is to shuffle the reference array and get one index from the array. You have 4 different links, when you call this function 3 times you have a good chance of getting the same page.

Try the following:



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

      

+3


source







All Articles