mirror of https://github.com/mpv-player/mpv
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:
parent
3353923f29
commit
b9c48ca8f3
|
@ -169,11 +169,9 @@ void playlist_shuffle(struct playlist *pl)
|
||||||
arr[n] = pl->first;
|
arr[n] = pl->first;
|
||||||
playlist_unlink(pl, pl->first);
|
playlist_unlink(pl, pl->first);
|
||||||
}
|
}
|
||||||
for (int n = 0; n < count; n++) {
|
for (int n = 0; n < count - 1; n++) {
|
||||||
int other = (int)((double)(count) * rand() / (RAND_MAX + 1.0));
|
int j = (int)((double)(count - n) * rand() / (RAND_MAX + 1.0));
|
||||||
struct playlist_entry *tmp = arr[n];
|
MPSWAP(struct playlist_entry *, arr[n], arr[n + j]);
|
||||||
arr[n] = arr[other];
|
|
||||||
arr[other] = tmp;
|
|
||||||
}
|
}
|
||||||
for (int n = 0; n < count; n++)
|
for (int n = 0; n < count; n++)
|
||||||
playlist_add(pl, arr[n]);
|
playlist_add(pl, arr[n]);
|
||||||
|
|
Loading…
Reference in New Issue