Home > Backend Development > C++ > Is `OrderBy(x => r.Next())` a Smart Way to Shuffle a List?

Is `OrderBy(x => r.Next())` a Smart Way to Shuffle a List?

DDD
Release: 2025-01-31 19:01:08
Original
614 people have browsed it

<.> r.next ()) `a sart way to shuffle a list? " /> Is `OrderBy(x =>
</p> <<> Is the <p> shuffle list wise? <strong> <<>
<code>OrderBy(x => r.Next())</code> When discussing the shuffle algorithm, some people recommend using the following code: </strong>
</p>
<p> <估> Evaluation </p> <div class=

var r = new Random();
var shuffled = ordered.OrderBy(x => r.Next());
Copy after login

This method is not an ideal shuffle method. Although it generates the only random number for each element, it is an O (N LOG N) operation, and there is a more effective O (N) algorithm. <原> Working principle

In essence, this method is distributed to elements randomly and sorted them based on these numbers. This ensures that each element appears in different positions, but the location is actually determined by the generated random number.

<替> Alternative method

It is recommended to use the Fisher-Yates shuffle algorithm of the DURSTENFELD version, which directly exchange elements. Can be implemented using such extensions like this:

<能> Performance optimization

In order to further optimize performance, the elements can be returned immediately when shuffling, thereby reducing unnecessary work: (This code is exactly the same as the previous code, repeated)

public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
    T[] elements = source.ToArray();
    for (int i = elements.Length - 1; i >= 0; i--)
    {
        int swapIndex = rng.Next(i + 1);
        yield return elements[swapIndex];
        elements[swapIndex] = elements[i];
    }
}
Copy after login

<说> Important description

Must use the right Random instance to avoid generating the same digital sequence multiple times and keep thread security.

">

The above is the detailed content of Is `OrderBy(x => r.Next())` a Smart Way to Shuffle a List?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template