Modified Fisher-Yates array shuffling algorithm
Hello Lovely Techies,
While building a customized Bingo Card in React JS I had to shuffle the(5 * 5 = 25 cells) game board upon every time the game refreshed i.e when the component mounted thereby using the componentDidMount() hook
This was the following slightly modified Fisher-Yates function that I came up with, note that the cell indexed 12 (middle cell) was not clickable, static and had to be part of the winning combination indexes.
export function shuffleArray(array, n) {
let i = array.length - 1;
for (; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
if(i === n || j === n) continue;
let temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
// n was the index number that wasn’t meant to be shuffled
// shuffle board except for the middle indexed cell everytime the component mounts
componentDidMount() {
const shuffledPosts = shuffleArray(this.state.board, 12)
this.setState({
board: shuffledPosts
});
}
Hope this helped