Home > Backend Development > C++ > How Can I Randomly Shuffle a Subset of a Collection Using LINQ?

How Can I Randomly Shuffle a Subset of a Collection Using LINQ?

DDD
Release: 2025-01-01 08:05:09
Original
209 people have browsed it

How Can I Randomly Shuffle a Subset of a Collection Using LINQ?

Randomly Shuffling a Subcollection in LINQ Using Fisher-Yates-Durstenfeld

When dealing with large datasets, obtaining a random shuffled collection of a specific size from a given collection becomes crucial. This commonly arises in scenarios involving randomized selection or sampling. Let's explore an optimal LINQ-based solution to this problem.

The Fisher-Yates-Durstenfeld shuffle algorithm offers an efficient and reliable approach to random shuffling. In this context, the goal is to produce a random subset of size 'n' from a collection of 'N' elements, where 'n' is less than or equal to 'N.'

To implement this algorithm using LINQ, we can leverage an extension method that encapsulates the shuffle operation. The following code snippet provides a comprehensive implementation:

public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
    if (source == null) throw new ArgumentNullException(nameof(source));
    if (rng == null) throw new ArgumentNullException(nameof(rng));

    return source.ShuffleIterator(rng);
}

private static IEnumerable<T> ShuffleIterator<T>(
    this IEnumerable<T> source, Random rng)
{
    var buffer = source.ToList();
    for (int i = 0; i < buffer.Count; i++)
    {
        int j = rng.Next(i, buffer.Count);
        yield return buffer[j];

        buffer[j] = buffer[i];
    }
}
Copy after login

In this implementation, the Shuffle extension method accepts an input sequence source and an instance of Random named rng. It creates a buffer list from the input sequence and iterates through it, randomly selecting elements. The selected elements are returned as an iterator, preserving the random ordering.

To utilize this extension method, simply append .Shuffle() to the input sequence followed by .Take(n), where n represents the desired size of the shuffled subcollection. For instance:

var randomItems = yourCollection.Shuffle().Take(n);
Copy after login

This Linq-based approach provides a concise and efficient solution for randomly shuffling and obtaining a subcollection of any size from a given collection. It is particularly suited for scenarios where a true randomization is required.

The above is the detailed content of How Can I Randomly Shuffle a Subset of a Collection Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template