Random playlist algorithm

后端 未结 12 1544
北恋
北恋 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:52

    You're going to have to allocate some memory, but it doesn't have to be a lot. You can reduce the memory footprint (the degree by which I'm unsure, as I don't know that much about the guts of C#) by using a bool array instead of int. Best case scenario this will only use (count / 8) bytes of memory, which isn't too bad (but I doubt C# actually represents bools as single bits).

        public static IEnumerable RandomIndexes(int count) {
            Random rand = new Random();
            bool[] used = new bool[count];
    
            int i;
            for (int counter = 0; counter < count; counter++) {
                while (used[i = rand.Next(count)]); //i = some random unused value
                used[i] = true;
                yield return i;
            }
        }
    

    Hope that helps!

提交回复
热议问题