Can someone help explain the Fisher Yates Array Shuffle

167 Views Asked by At

So I am trying to get an understanding for array shuffling.

I came across this article: https://bost.ocks.org/mike/shuffle/

But I am confused.

function shuffle(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}

Here are my questions:

On line 2 "m" is defined, but I don't understand why "t" and "i" are part of that definition. Are "t" and "i" being defined as true?

The while loop condition is: "as long as m=true". However, as far as I can tell, nothing happens to the length of the array, so won't it stay true indefinitely?

The last part of my confusion is this:

  t = array[m];
    array[m] = array[i];
    array[i] = t;

So "t" equals a value in the array. "m" is the length of the array and this tells "t" which value to choose.

Then that value is replaced with another value in the array. This new value uses the previously generated random number to choose a different value (I can't tell if there is a possibility to choose the same value).

This new value is re-defined as "t". This part I just don't understand.

It almost seems to be looping in on itself with array[i] = t and the whole thing starting all over again.

I hope someone can help.

Thanks in advance!

1

There are 1 best solutions below

7
gog On

That code is indeed confusing. It would be better to declare variables right where they belong. Does this make more sense?

function shuffle(array) {
    let m = array.length

    // While there remain elements to shuffle…
    while (m) {

        // Pick a remaining element…
        let i = Math.floor(Math.random() * m)

        m--

        // And swap it with the current element.
        let temp = array[m]
        array[m] = array[i]
        array[i] = temp
    }

    return array
}