I have a function here that swap items randomly from an array;
const switch = function(array) {
let switchArr = array.slice();
for (let i = switchArr.length-1; i >=0; i--) {
let randomIndex = Math.floor(Math.random() * (i+1));
let itemAtIndex = switchArr[randomIndex];
switchArr[randomIndex] = shuffledArr[i];
switchArr[i] = itemAtIndex;
}
return switchArr;
};
Can someone explain how is this code swap the array elements:
let randomIndex = Math.floor(Math.random() * (i+1));
let itemAtIndex = switchArr[randomIndex];
switchArr[randomIndex] = shuffledArr[i];
switchArr[i] = itemAtIndex;
let's say we have an array:
let arrTest = [1,2,3,4,5];
Basically the function will start with i = 4 (length is 5 - 1) and loop until i >=0 (4, 3, 2, 1);
Now this part trips me:
let randomIndex = Math.floor(Math.random() * (i+1));
MDN said that if we want a random function between two func it must be like this:
Math.floor(Math.random() * (max - min)) + min;
Contrary to what I see there. Also It's kinda confusing switchArr
and
itemAtIndex
swap items.
I really need an analogy per iteration in order to get this into my mind.
Anyone who can understand and explain this?