fix(queue): implement proper Fisher-Yates shuffle algorithm
Previous implementation had a critical bug in the shuffle algorithm that used the same seed value for all iterations, resulting in weak/predictable shuffling. Changes: - Add rand crate dependency for proper PRNG - Fix Fisher-Yates to use unique random value per iteration - Use StdRng with timestamp-based seed for reproducible randomness - Each shuffle iteration now gets a new random number from the RNG This fixes shuffle working inconsistently across different contexts (albums, playlists, continuous play). cc
This commit is contained in:
1 parent
603b794838
commit
0bbf6435b4
2 files changed
+11
-3
No files matched your search
@@ -45,6 +45,9 @@ anyhow = "1"
|
||||
log = "0.4"
|
||||
env_logger = "0.11"
|
||||
|
||||
# Random number generation (for shuffle)
|
||||
rand = "0.8"
|
||||
|
||||
# Audio playback
|
||||
rodio = { version = "0.19", features = ["symphonia-all"] }
|
||||
symphonia = { version = "0.5", features = ["all"] }
|
||||
|
||||
@@ -508,15 +508,20 @@ impl QueueManager {
|
||||
fn regenerate_shuffle_order_internal(state: &mut InternalState) {
|
||||
let mut order: Vec<usize> = (0..state.tracks.len()).collect();
|
||||
|
||||
// Fisher-Yates shuffle
|
||||
// Fisher-Yates shuffle with proper PRNG
|
||||
use rand::{Rng, SeedableRng};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
// Create seeded RNG from current timestamp
|
||||
let seed = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos() as usize;
|
||||
.as_nanos() as u64;
|
||||
let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
|
||||
|
||||
// Proper Fisher-Yates shuffle - each iteration gets a NEW random number
|
||||
for i in (1..order.len()).rev() {
|
||||
let j = (seed.wrapping_mul(i + 1)) % (i + 1);
|
||||
let j = rng.gen_range(0..=i);
|
||||
order.swap(i, j);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user