From b730c6637a1b07a00cd1df23591faeabd0fb0cfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=B6rdle=20Bot?= Date: Wed, 3 Dec 2025 17:34:23 +0100 Subject: [PATCH] Fix random song selection bias in daily puzzle generation --- lib/dailyPuzzle.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/dailyPuzzle.ts b/lib/dailyPuzzle.ts index 3c7a00c..4b58b8f 100644 --- a/lib/dailyPuzzle.ts +++ b/lib/dailyPuzzle.ts @@ -49,13 +49,15 @@ export async function getOrCreateDailyPuzzle(genre: Genre | null = null) { // Calculate total weight const totalWeight = weightedSongs.reduce((sum, item) => sum + item.weight, 0); - // Pick a random song based on weights + // Pick a random song based on weights using cumulative weights + // This ensures proper distribution and handles edge cases let random = Math.random() * totalWeight; - let selectedSong = weightedSongs[0].song; + let selectedSong = weightedSongs[weightedSongs.length - 1].song; // Fallback to last song + let cumulativeWeight = 0; for (const item of weightedSongs) { - random -= item.weight; - if (random <= 0) { + cumulativeWeight += item.weight; + if (random <= cumulativeWeight) { selectedSong = item.song; break; } @@ -156,11 +158,13 @@ export async function getOrCreateSpecialPuzzle(special: Special) { const totalWeight = weightedSongs.reduce((sum, item) => sum + item.weight, 0); let random = Math.random() * totalWeight; - let selectedSpecialSong = weightedSongs[0].specialSong; + let selectedSpecialSong = weightedSongs[weightedSongs.length - 1].specialSong; // Fallback to last song + // Pick a random song based on weights using cumulative weights + let cumulativeWeight = 0; for (const item of weightedSongs) { - random -= item.weight; - if (random <= 0) { + cumulativeWeight += item.weight; + if (random <= cumulativeWeight) { selectedSpecialSong = item.specialSong; break; }