Random playlist algorithm

后端 未结 12 1546
北恋
北恋 2020-12-09 04:58

I need to create a list of numbers from a range (for example from x to y) in a random order so that every order has an equal chance.

I need this for a music player I

12条回答
  •  感动是毒
    2020-12-09 05:32

    From a logical standpoint, it is possible. Given a list of n songs, there are n! permutations; if you assign each permutation a number from 1 to n! (or 0 to n!-1 :-D) and pick one of those numbers at random, you can then store the number of the permutation that you are currently using, along with the original list and the index of the current song within the permutation.

    For example, if you have a list of songs {1, 2, 3}, your permutations are:

    0: {1, 2, 3}
    1: {1, 3, 2}
    2: {2, 1, 3}
    3: {2, 3, 1}
    4: {3, 1, 2}
    5: {3, 2, 1}
    

    So the only data I need to track is the original list ({1, 2, 3}), the current song index (e.g. 1) and the index of the permutation (e.g. 3). Then, if I want to find the next song to play, I know it's third (2, but zero-based) song of permutation 3, e.g. Song 1.

    However, this method relies on you having an efficient means of determining the ith song of the jth permutation, which until I've had chance to think (or someone with a stronger mathematical background than I can interject) is equivalent to "then a miracle happens". But the principle is there.

提交回复
热议问题