Question regarding shuffling array


#1

Can anyone explain why and how swapping is done on these two lines?

/*
input[randomIndex] = input[i]; 
        input[i] = itemAtIndex;
*/

Array.prototype.shuffle = function() {
    var input = this;
     
    for (var i = input.length-1; i >=0; i--) {
     
        var randomIndex = Math.floor(Math.random()*(i+1)); 
        var itemAtIndex = input[randomIndex]; 
         
        input[randomIndex] = input[i]; 
        input[i] = itemAtIndex;
    }
    return input;
}
 
var tempArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
tempArray.shuffle();
 
// and the result is...
alert(tempArray);

#2

This diagram from the tutorial is the key:

We need a temporary location to store the value we are swapping. The “4” is stored at itemAtIndex. The rest should be straightforward. Once the value is stored, those two lines swap the values between both array locations.

Does that help? :slight_smile:


#3

It does thanks! :grinning: