0

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?

  • `switch` is a keyword dont use it for variable name – Omaim Dec 02 '17 at 10:36
  • `randomIndex` has to be a number between zero (`min`) and the number of "remaining" elements (`max`), hence `Math.floor(Math.random() * (max - min)) + min` is the same as `Math.floor(Math.random() * max)` – Andreas Dec 02 '17 at 10:37
  • Possible duplicate of [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – Durga Dec 02 '17 at 10:41
  • Mind explaining it to me in details? please give some analogy of iteration I would appreciate and accept your answer. check. –  Dec 02 '17 at 10:42
  • Tony, the link Durga provided itself contains a link to an animated step by step explanation of the algorithm in its accepted answer. – Thomas Hennes Dec 02 '17 at 11:14

0 Answers0