Shuffle Elements of Array Randomly Fisher-Yates (Knuth) shuffle

In this blog we will discuss how to shuffle elements of array randomly using Fisher-Yates (Knuth) algorithm. We will also add some additional checks later to ensure we get shuffled array in any case i.e. if array has 2 or more elements. If array has one element or empty we can’t produce shuffled array.

To shuffle an array, you can use the Fisher-Yates (Knuth) shuffle algorithm. It basically generates a random index between 0 (inclusive) and the current index (inclusive) and then swaps the value at the randomly generated index with the value at the current index. This operation is performed for all the values in the array by executing a loop.

function shuffleArray(array) {
  // Use the Fisher-Yates (Knuth) shuffle algorithm
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    // Swap array[i] and array[j]
    [array[i], array[j]] = [array[j], array[i]];
  }
}

// Example usage
const myArray = [1, 2, 3, 4, 5];
shuffleArray(myArray);
console.log(myArray);

Math.random() generates a value between 0 and 1 (exclusive) , think of i as current index and j as random index generated. Hence Math.random()*(i+1) would generate a value between 0 and current Index(inclusive).

Math.floor() will convert the generated random value to integer before decimal point. So 2.3 would be converted to 2, 0.5 would be converted to 0 . Effectively value of j will be integer and can be anything between 0 and current index value (inclusive) . We take this random index value and find swap the value present at index j with value at index i.

You need to be logged in to view the rest of the content. Please . Not a Member? Join Us

Leave a Comment

Pin It on Pinterest

Scroll to Top