Array Shuffling - The Fisher-Yates algorithm in javascript
The more we shuffle a deck of cards, the worse is the shuffle♣
This is a very famous shuffling algorithm, it was created by Fisher and Yates
It consists of iterating each position of the array starting by the last array position and swapping the current position with a random position.
The random position is lesser than the current position to make sure we don’t re-shuffle.
Diagram:
Code:
//Fisher-Yates algorithm | |
function shuffle(array){ | |
for(let i = array.length - 1; i>0; i--){ | |
const randomIndex = Math.floor(Math.random() * (i+1)) | |
const temp = array[i]; | |
array[i] = array[randomIndex]; | |
array[randomIndex] = temp; | |
} | |
return array; | |
} | |
console.log(shuffle([1,2,3,4,5,6,7,8])) |
If you liked this post you might also like the perks🐱🏍 you will get if you subscribe😁