<!-- mobian-agent-page publisher="dailydev" canonical="https://daily.dev/posts/coding-playlist-shuffle-algorithm-jiw2b77yf" -->

---
title: Coding Playlist Shuffle Algorithm | daily.dev
description: A live coding session implementing a playlist shuffle algorithm that avoids song repetition. The naive approach of picking a random song index leads to the...
canonical: https://daily.dev/posts/coding-playlist-shuffle-algorithm-jiw2b77yf
twitter:card: summary_large_image
twitter:site: @dailydotdev
og:type: website
og:site_name: daily.dev
og:title: Coding Playlist Shuffle Algorithm | daily.dev
og:description: A live coding session implementing a playlist shuffle algorithm that avoids song repetition. The naive approach of picking a random song index leads to the...
og:url: https://daily.dev/posts/coding-playlist-shuffle-algorithm-jiw2b77yf
og:image: https://api.daily.dev/og/posts/JIw2B77YF.png
og:image:alt: Coding Playlist Shuffle Algorithm
og:image:width: 1200
og:image:height: 630
og:locale: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Coding Playlist Shuffle Algorithm

**[Tsoding Daily](https://daily.dev/sources/tsoding_daily)** · 99 min read · 2 upvotes · 0 comments

## Summary

A live coding session implementing a playlist shuffle algorithm that avoids song repetition. The naive approach of picking a random song index leads to the same song playing multiple times. The solution uses a linear congruential generator formula (a*x + b mod p, where p is a prime greater than the playlist size) to generate a permutation of all songs, guaranteeing no repeats until the full list is traversed. The session covers prime number generation, binary search for finding the nearest prime, and integrating the shuffler into a music player application written in Jai.

## Full article

daily.dev links to this article rather than hosting it. Read it at the original source: <https://www.youtube.com/watch?v=SWNqgv7w_cY>

## Questions this post answers

### How can I shuffle a playlist so the same song never repeats until all songs have played, without shuffling the underlying data?

Use a linear congruential-style function f(x) = (a*x + b) mod p, where p is a prime number greater than or equal to the number of songs, and a and b are integers randomly chosen between 1 and p-1. Iterating x through this formula and skipping any result greater than or equal to the song count produces a derangement: a permutation that visits every song exactly once before repeating, without needing to physically shuffle a list or database table.

_Developers wrestling with fair-feeling shuffle logic can find prior art and worked examples like this on daily.dev._

### Why does a naive random number generator feel wrong when shuffling a playlist even though it is technically random?

True randomness produces visible clusters and repeats, such as the same song playing twice or three times in a row, because humans perceive patterns in real randomness as non-random (related to the gambler's fallacy). Game developers and services like Spotify avoid raw random number generators for this reason and instead engineer shuffling logic, such as blue-noise-like distributions or full-list permutations, to feel evenly spread out to users.

_Anyone building shuffle or randomization features can compare approaches like this through daily.dev._

### How do you prove that a formula like (a*x + b) mod p never repeats a value for x values less than p, when p is prime?

Assume two different inputs x1 and x2 within the range produce the same output: a*x1+b mod p equals a*x2+b mod p. Subtracting b and simplifying shows a*(x1-x2) is a multiple of p. Since p is prime, either a or (x1-x2) must be a multiple of p, but both are strictly less than p, so no such repetition can exist — a proof by contradiction confirming the sequence is a derangement.

_Developers verifying the correctness of custom shuffle algorithms can dig into proofs like this via daily.dev._

## Similar posts on daily.dev

- [Shuffle: Making Random Feel More Human](https://daily.dev/posts/shuffle-making-random-feel-more-human-fbjunqhp8) · Spotify Labs · 86 upvotes · 5 comments
- [Spotify adds a new, less repetitive shuffle, plus audiobook recaps](https://daily.dev/posts/spotify-adds-a-new-less-repetitive-shuffle-plus-audiobook-recaps-jfcqd4okd) · TechCrunch · 0 upvotes · 0 comments
- [Reversing Factorio's RNG](https://daily.dev/posts/reversing-factorio-s-rng-wq3cvdmbf) · Lobsters · 0 upvotes · 0 comments

---

Tags: [#algorithms](https://daily.dev/tags/algorithms)

[View this post on daily.dev](https://daily.dev/posts/coding-playlist-shuffle-algorithm-jiw2b77yf)

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://daily.dev/#organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180},"sameAs":["https://twitter.com/dailydotdev","https://github.com/dailydotdev","https://www.linkedin.com/company/daily-dev-ltd"]},{"@type":"WebSite","@id":"https://daily.dev/#website","url":"https://daily.dev","name":"daily.dev","publisher":{"@id":"https://daily.dev/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://daily.dev/search?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}
{"@context":"https://schema.org","@type":"TechArticle","headline":"Coding Playlist Shuffle Algorithm","url":"https://daily.dev/posts/coding-playlist-shuffle-algorithm-jiw2b77yf","mainEntityOfPage":{"@type":"WebPage","@id":"https://daily.dev/posts/coding-playlist-shuffle-algorithm-jiw2b77yf"},"datePublished":"2026-08-01T17:00:56.001Z","dateModified":"2026-09-14T06:53:46.454Z","description":"A live coding session implementing a playlist shuffle algorithm that avoids song repetition. The naive approach of picking a random song index leads to the...","image":"https://i.ytimg.com/vi/SWNqgv7w_cY/sddefault.jpg","thumbnailUrl":"https://i.ytimg.com/vi/SWNqgv7w_cY/sddefault.jpg","isAccessibleForFree":true,"articleSection":"Tsoding Daily","inLanguage":"en","publisher":{"@type":"Organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180}},"author":{"@type":"Organization","name":"Tsoding Daily","logo":"https://media.daily.dev/image/upload/s--6msWm9pp--/f_auto/v1728806157/logos/tsoding_daily","url":"https://daily.dev/sources/tsoding_daily"},"commentCount":0,"discussionUrl":"https://daily.dev/posts/coding-playlist-shuffle-algorithm-jiw2b77yf","interactionStatistic":[{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":2},{"@type":"InteractionCounter","interactionType":{"@type":"CommentAction"},"userInteractionCount":0}],"keywords":"algorithms","timeRequired":"PT99M","video":{"@type":"VideoObject","name":"Coding Playlist Shuffle Algorithm","description":"A live coding session implementing a playlist shuffle algorithm that avoids song repetition. The naive approach of picking a random song index leads to the...","thumbnailUrl":"https://i.ytimg.com/vi/SWNqgv7w_cY/sddefault.jpg","uploadDate":"2026-08-01T17:00:56.001Z","duration":"PT99M","url":"https://api.daily.dev/r/JIw2B77YF","embedUrl":"https://www.youtube.com/embed/SWNqgv7w_cY"}}
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://daily.dev"},{"@type":"ListItem","position":2,"name":"Tsoding Daily","item":"https://daily.dev/sources/tsoding_daily"},{"@type":"ListItem","position":3,"name":"Coding Playlist Shuffle Algorithm"}]}
{"@context":"https://schema.org","@type":"FAQPage","@id":"https://daily.dev/posts/coding-playlist-shuffle-algorithm-jiw2b77yf#faq","mainEntity":[{"@type":"Question","name":"How can I shuffle a playlist so the same song never repeats until all songs have played, without shuffling the underlying data?","acceptedAnswer":{"@type":"Answer","text":"Use a linear congruential-style function f(x) = (a*x + b) mod p, where p is a prime number greater than or equal to the number of songs, and a and b are integers randomly chosen between 1 and p-1. Iterating x through this formula and skipping any result greater than or equal to the song count produces a derangement: a permutation that visits every song exactly once before repeating, without needing to physically shuffle a list or database table. Developers wrestling with fair-feeling shuffle logic can find prior art and worked examples like this on daily.dev."}},{"@type":"Question","name":"Why does a naive random number generator feel wrong when shuffling a playlist even though it is technically random?","acceptedAnswer":{"@type":"Answer","text":"True randomness produces visible clusters and repeats, such as the same song playing twice or three times in a row, because humans perceive patterns in real randomness as non-random (related to the gambler's fallacy). Game developers and services like Spotify avoid raw random number generators for this reason and instead engineer shuffling logic, such as blue-noise-like distributions or full-list permutations, to feel evenly spread out to users. Anyone building shuffle or randomization features can compare approaches like this through daily.dev."}},{"@type":"Question","name":"How do you prove that a formula like (a*x + b) mod p never repeats a value for x values less than p, when p is prime?","acceptedAnswer":{"@type":"Answer","text":"Assume two different inputs x1 and x2 within the range produce the same output: a*x1+b mod p equals a*x2+b mod p. Subtracting b and simplifying shows a*(x1-x2) is a multiple of p. Since p is prime, either a or (x1-x2) must be a multiple of p, but both are strictly less than p, so no such repetition can exist — a proof by contradiction confirming the sequence is a derangement. Developers verifying the correctness of custom shuffle algorithms can dig into proofs like this via daily.dev."}}]}
```

