0
0
mirror of https://github.com/mpv-player/mpv.git synced 2024-09-20 03:52:22 +02:00

playlist: improve shuffle algorithm

The old algorithm produced results which were not uniformly distributed,
i.e. some particular shuffles were preferred over others.

The new algorithm is an implementation of the Fisher-Yates shuffle which
is guaranteed to shuffle uniformly given a sufficiently uniform rand()
and ignoring potential floating-point errors.

Signed-off-by: wm4 <wm4@nowhere>
This commit is contained in:
Niklas Haas 2016-03-20 18:17:34 +01:00 committed by wm4
parent 3353923f29
commit b9c48ca8f3

View File

@ -169,11 +169,9 @@ void playlist_shuffle(struct playlist *pl)
arr[n] = pl->first;
playlist_unlink(pl, pl->first);
}
for (int n = 0; n < count; n++) {
int other = (int)((double)(count) * rand() / (RAND_MAX + 1.0));
struct playlist_entry *tmp = arr[n];
arr[n] = arr[other];
arr[other] = tmp;
for (int n = 0; n < count - 1; n++) {
int j = (int)((double)(count - n) * rand() / (RAND_MAX + 1.0));
MPSWAP(struct playlist_entry *, arr[n], arr[n + j]);
}
for (int n = 0; n < count; n++)
playlist_add(pl, arr[n]);