dimanche 5 septembre 2021

How does this Javascript deck shuffling function work? (for loops and arrays) [duplicate]

I want to include this code (not mine, copied from a different answer) into my javascript/html card game to randomly shuffle cards before they are shown, but I cannot figure out the logic that makes it work:

var deck = [1, 2, 3, 4, 5, 6, 7, 8, 9];
document.write(JSON.stringify(shuffle(deck), 0, 1));

function shuffle (anArray) {
  var i, j, x, l = anArray.length; // The variables i, j, x, l all equal the deck length, which is 9
  for (i = 0; i < l; i++) { // do this 9 times
    j = rdmInt(l); // j is a random number between 0 and 8
    x = anArray[i]; // x is the thing in the array at position i, so x is 1,2,3,4,5,6,7,8,9 each repetition
    anArray[i] = anArray[j]; // the thing in i of array is now whatever was in position j
    anArray[j] = x; // whatever is in position j is now whatever is in position x( which is i)
  }
  return anArray;
}

function rdmInt (max) {
  return Math.floor(Math.random() * max);
}

As you can see, I have tried to comment in my thought process as I try to make sense of the code, but I just don't understand how it shuffles all the numbers in deck. Please can someone edit/add comments to explain it as simple as possible. I understand basic Javascript (functions, returns, for loops etc), so you don't need to explain those bits. Thanks so much.




Aucun commentaire:

Enregistrer un commentaire