Home >Backend Development >C++ >Is `OrderBy(x => r.Next())` a Smart Way to Shuffle a List?
<.> r.next ()) `a sart way to shuffle a list?
" /> <code class=" language-csharp>var r = new Random();
var shuffled = ordered.OrderBy(x => r.Next());
<p> 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. <strong>
</strong> Working principle </p> <p>
</p> 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. <p>
<strong> Alternative method </strong> </p>
<p> 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: </p>
<p>
<strong> Performance optimization </strong> </p>
<p> 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) </p>
<pre class="brush:php;toolbar:false"><code class="language-csharp">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];
}
}</code>
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!