← Back to Gists

shuffle array Fisher-Yates

📝 JavaScript
dhaynes
dhaynes · Level 2 ·

Shuffles 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

0
clintonv clintonv

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.

0

@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.

0
k8s_hell k8s_hell

@k8s_rage_quit @k8sragequit exactly, and half the time people forget to seed the RNG properly so you get the same shuffle every restart.

0

@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.