Algorithms · Counting & data
Shuffle algorithms
Why Spotify made shuffle less random. True randomness puts three songs by the same artist in a row. People hated it.
The problem
Imagine you hit shuffle on a playlist and hear three songs in a row by the same artist. You'd think the app was broken. In 2014, Spotify engineer Lukáš Poláček wrote in the post "How to shuffle songs?" that listeners were complaining exactly this: shuffle didn't feel random.
The twist is that the shuffle was fine. Truly random orders often clump songs by the same artist, and people read clumps as a bug.
The obvious way
The standard truly-random shuffle is Fisher–Yates: walk the list and swap each song with a randomly chosen earlier spot. Every ordering is equally likely. That's the problem: orderings with two songs from one artist side by side are plentiful, so they show up often.
The clever idea
Think of hanging photos on a wall. You wouldn't throw them up at random; you'd space each series evenly. Spotify did something like that: spread each artist's songs roughly evenly across the playlist, with random offsets so it still feels unpredictable. The post says it was inspired by dithering.
My version below is a sketch of that idea, not Spotify's exact code. Each artist gets evenly spaced positions between 0 and 1, shifted by a random offset and nudged by jitter. Then we sort all songs by position.
How the code does it
Fisher–Yates is the fair shuffle: no artist is treated specially, so same-artist neighbours happen by pure chance. The counter checks each neighbouring pair and tallies matches, and the 200-trial loop averages that so one lucky shuffle doesn't fool us.
In the spread shuffle, Ada's 8 songs sit about every 1/8 of the way along, and Di's 2 sit about halfway apart. Then one sort merges everyone into a single order. Run it and compare the bars: the spread version should show far fewer back-to-back pairs, and the two grids show why it feels better.
Trade-offs
The spread shuffle is less random in the mathematical sense: some orders can barely appear, and it needs to know who the artist is for every song. Don't use it when you need true fairness, like drawing raffle winners or dealing cards. Use Fisher–Yates there.
Where else you'll see it
Dithering-style spreading shows up in image rendering, where it avoids visible blobs of one colour, and in anywhere you want "random but evenly mixed", like rotating ads or mixing quiz questions across topics.
An artist has 4 songs in a 20-song playlist. Roughly how far apart does the spread shuffle place them?
- Back to back
- About every 5th song
- Always at the very end
Show the answer
About every 5th song. Gaps are 1/n of the playlist, so 4 songs means about 1/4 of 20, or roughly every 5 songs, with offset and jitter making it vary.
- Change counts to give Ada 12 songs
- Set jitter 0.3 to 3
- Raise trials from 200 to 1000
- Remove the offset line's randomness
The code
javascript, with what each line means beside it. It compares the clever way with a perfectly random shuffle.
const counts = { Ada: 8, Bo: 6, Cy: 4, Di: 2 };Say how many songs each artist hasconst playlist = Object.entries(counts).flatMap(([a, n]) => Array(n).fill(a));Build a 20-song playlist, one name per song function fisherYates(list) {Define the truly random shuffle const a = [...list];Copy the list so the original stays safe for (let i = a.length - 1; i > 0; i--) {Walk backwards from the last position const j = Math.floor(Math.random() * (i + 1));Pick a random spot at or before here [a[i], a[j]] = [a[j], a[i]];Swap the two songs } return a;Hand back the shuffled copy} function spreadShuffle(list) {Define the spread shuffle const scored = [];Start an empty list of scored songs for (const artist of new Set(list)) {For each artist in the playlist const n = list.filter(s => s === artist).length;Count how many songs they have const offset = Math.random() / n;Pick one random shift within a gap for (let k = 0; k < n; k++) {For each of their songs const jitter = (Math.random() - 0.5) * 0.3 / n;Make a small random nudge scored.push({ artist, pos: k / n + offset + jitter });Place it at an even spot plus shift } } scored.sort((x, y) => x.pos - y.pos);Sort all songs by their position return scored.map(s => s.artist);Return just the artist names} function clumps(order) {Define a clump counter let pairs = 0;Start counting at zero for (let i = 1; i < order.length; i++) {Look at each neighbouring pair if (order[i] === order[i - 1]) pairs++;If both songs share an artist, count it } return pairs;Return the count} let randomTotal = 0, spreadTotal = 0;Set up two running totalsfor (let t = 0; t < 200; t++) {Repeat the experiment 200 times randomTotal += clumps(fisherYates(playlist));Add clumps from a random shuffle spreadTotal += clumps(spreadShuffle(playlist));Add clumps from a spread shuffle}show([randomTotal / 200, spreadTotal / 200], "Avg back-to-back pairs: Fisher–Yates vs spread");Show both averages as bars const rows = o => [o.slice(0, 10), o.slice(10)];Split an order into two rows of tenshow(rows(fisherYates(playlist)), "Fisher–Yates sample");Show one random shuffle as a gridshow(rows(spreadShuffle(playlist)), "Spread sample");Show one spread shuffle as a grid- the swap lines 6–8Each position trades with a random spot at or before it. That gives every possible order the same chance, clumps included.
- even gaps lines 16–17An artist with n songs gets gaps of 1/n. The shared random offset slides the whole row, so the start differs every time.
- jitter lines 19–20Without jitter, the order would repeat in patterns. A small nudge keeps spacing even but not robotic.
- sorting does the mixing line 23Songs from different artists get interleaved simply because their positions land in between each other.
Read more
- engineering.atspotify.com: Shuffle algorithms
- Ask Bento: Why is Fisher–Yates truly fair?
- Ask Bento: What does Array.sort do internally?
- Ask Bento: How does image dithering work?
Run it. Then change it.
The code runs right in the page and draws as it goes. Free, nothing to install.