Shuffle with Fisher–Yates
Write the code, see it run, pass the checks.
The problem
- medium
- Code
- Pro
Write shuffle(items, random), where random defaults to Math.random and returns a number from 0 up to but not including 1. Return a new, shuffled array using the Fisher–Yates method, in exactly this order so the checks can repeat it: copy items, then for each index i from the last one down to 1, pick j as random() times (i + 1), rounded down, and swap the items at i and j. So an array of n items calls random exactly n minus 1 times, and empty or one-item arrays don't call it at all. Don't change items.
Your code must pass
- Calls random n minus 1 times
- Swaps in the Fisher–Yates order
- Returns a new array with the same items and leaves the input alone
- Handles empty and one-item arrays without calling random
- Gives all 6 orders of 3 items about equally often