Exercise 13: Shuffle Array (Fisher-Yates)
Problem Statement
Create a function `shuffle(arr)` that randomly shuffles array.
Example: shuffle([1, 2, 3, 4]) → [3, 1, 4, 2] (random)
Sample Output:
shuffle([1, 2, 3, 4]) => [3, 1, 4, 2] (random) shuffle([1, 2, 3]) => [2, 3, 1] (random)
Solution
const shuffle = (arr) => {
const result = [...arr];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
};Explanation
Overall Goal:
- Array ko randomly shuffle karna (Fisher-Yates algorithm).
Real world:
- Randomization: quiz questions shuffle.
- Games: card shuffling.