Hone logo
Hone
Problems

Shuffle an Array in JavaScript

You're tasked with creating a function that randomly shuffles the elements of an array. This is a fundamental operation with numerous applications, from randomizing the order of questions in a quiz to shuffling a deck of cards in a game. Your goal is to implement an efficient and fair shuffling algorithm.

Problem Description

Implement a JavaScript function, shuffleArray(array), that takes an array as input and returns a new array with its elements randomly reordered. The original array should not be modified. The shuffling should be "fair," meaning that every possible permutation of the array elements should have an equal probability of occurring.

Key Requirements:

  • The function must accept a single argument: an array of any data type.
  • The function must return a new array containing the shuffled elements. The original array must remain unchanged.
  • The shuffling algorithm should be reasonably efficient.
  • The shuffling should be demonstrably random (as much as possible with standard pseudo-random number generators).

Expected Behavior:

Given an input array, the function should produce an output array where the elements are in a random order. For the same input array, multiple calls to the function should ideally produce different shuffled outputs.

Edge Cases:

  • Empty array: The function should gracefully handle an empty input array, returning an empty array.
  • Array with one element: The function should return a new array containing that single element.

Examples

Example 1:

Input: [1, 2, 3, 4, 5]
Output: [3, 1, 5, 2, 4] (This is just one possible outcome, the output will vary)
Explanation: The original elements are reordered randomly.

Example 2:

Input: ["apple", "banana", "cherry"]
Output: ["cherry", "apple", "banana"] (This is just one possible outcome)
Explanation: String elements are also shuffled correctly.

Example 3:

Input: []
Output: []
Explanation: An empty input array results in an empty output array.

Constraints

  • The input array will be a valid JavaScript array.
  • The size of the input array can range from 0 to 1000 elements.
  • The elements within the array can be of any JavaScript data type (numbers, strings, objects, etc.).
  • The solution should aim for a time complexity of O(n), where n is the number of elements in the array.

Notes

Consider using the Fisher-Yates (also known as Knuth) shuffle algorithm. This algorithm is a widely accepted and efficient method for generating unbiased random permutations. Remember that JavaScript's Math.random() is a pseudo-random number generator, so perfect randomness is not achievable, but this algorithm aims for uniform distribution of permutations. When implementing, ensure you are working with a copy of the original array.

Loading editor...
javascript