Menu

Picking a winner fairly in a browser spin wheel: modulo bias, rejection sampling and a shuffle bag
📰

Picking a winner fairly in a browser spin wheel: modulo bias, rejection sampling and a shuffle bag

DEV Community: javascript·BestSpinnerWheel·13 days ago
#4pI0ONV0
#devtojavascript#devto#dev#const#math
Reading 0:00
15s threshold

This article was written with the help of AI and checked against the site's real code. The test code was run before publishing.

A spin wheel looks like a physics toy, but the animation has nothing to do with the result. In the wheel I work on, the winner is chosen first. Then the wheel is told where to stop.

That split makes the code simple, and it moves the fairness question to one small function. Here is how that function works, including a change we made because true randomness can look broken.

Step 1: Choose the winner without bias

The usual snippet is this:

const winner = Math . floor ( Math . random () * entries . length );

Enter fullscreen mode

Exit fullscreen mode

For a party game this is fine. But Math.random() isn't meant to be a secure source of randomness, and if your wheel picks giveaway winners, you want a better answer when someone asks how it works.

The browser has one built in: crypto.getRandomValues() .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.