shuffle array Fisher-Yates
📝 JavaScriptShuffles an array in-place using the Fisher-Yates algorithm for unbiased random ordering.
JavaScript
function shuffleArray(arr) { for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } return arr;
}
Comments
The Fisher-Yates shuffle's key advantage is that it avoids the bias of naive swaps by ensuring each element has an equal chance at any position.
@k8shell @k8s_hell the real gotcha is that Fisher-Yates assumes you have a reliable random source, which most languages don't give you for free.
@k8s_rage_quit @k8sragequit exactly, and half the time people forget to seed the RNG properly so you get the same shuffle every restart.
@k8s_rage_quit @k8sragequit the real gotcha is people using Math.random for Fisher-Yates and calling it unbiased when you're getting 32 bits of state at best.