简体   繁体   中英

Shuffle Numbers and Generate Same Sequence of Numbers in every Execution

Below snippet shuffle numbers And changes sequence of numbers in every execution:

Enumerable.Range(1, 1000).OrderBy(r => Guid.NewGuid()).ToList();

BUT I want shuffle numbers and generate a same sequence of numbers in every execution of application?

It is more efficient to use an algorithm like Fisher-Yates shuffle to reorder the items. The run-time complexity of OrderBy is O(N log N) while Fisher-Yates shuffle is O(N) .

Also, to provide random numbers you should use the Random class, not Guid.NewGuid which serves a completely different purpose and just happens to create something that is random (at a higher cost).

I prefer to implement the shuffle as an extension method:

public static class ListExtensions
{
    public static IList<T> Shuffle<T>(this IList<T> list, Random random)
    {
        for (var i = list.Count; i > 1; i -= 1)
        {
            var j = random.Next(i); 
            var temp = list[j];
            list[j] = list[i - 1];
            list[i - 1] = temp;
        }
        return list;
    }
}

You can achieve the desired result by providing a Random instance with a specific seed (in this case 0). This will ensure that the sequence of random numbers generated are the same each time the code executes:

var shuffledList = Enumerable.Range(0, 1000).ToList().Shuffle(new Random(0));

Instead of using an O(n log n) sort to shuffle (never mind the overhead of generating the Guid values), you should use Random and the standard O(n) Fisher - Yates shuffle . Then you can give the Random object the same seed with every execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM