Modified Fisher-Yates array shuffling algorithm

2 Minute Tech Reads
1 min readJun 9, 2021

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

--

--

2 Minute Tech Reads

Software Dev, qualified lawyer, salesman, pro telemarketer, travel bug, meditator/energy healer, self help enthusiast, aspiring Tech Entrepreneur & family man