get a sample of 5 elements from an array without replacement in csharp

To get a random sample of 5 elements from an array without replacement in c#, you need to use the Random class to generate a sequence of unique random indices and then retrieve the corresponding array elements. Here's an example implementation:

main.cs
public static T[] SampleWithoutReplacement<T>(T[] population, int sampleSize)
{
    if (population.Length < sampleSize)
    {
        throw new ArgumentException("Sample size cannot be greater than population size.");
    }

    var random = new Random();
    var sample = new T[sampleSize];
    var populationIndices = Enumerable.Range(0, population.Length).ToArray();

    for (int i = 0; i < sampleSize; i++)
    {
        int randomIndex = random.Next(populationIndices.Length);
        int populationIndex = populationIndices[randomIndex];
        sample[i] = population[populationIndex];
        populationIndices[randomIndex] = populationIndices[populationIndices.Length - 1];
        Array.Resize(ref populationIndices, populationIndices.Length - 1);
    }

    return sample;
}
787 chars
23 lines

This method takes the population array as its first argument and the desired sample size as its second argument. It throws an ArgumentException if the sample size is greater than the population size. It creates a new instance of the Random class to generate random indices. It initializes an empty sample array with the specified sample size. It creates an array of indices corresponding to the population array. It then enters a loop where it generates a random index, retrieves the corresponding population element, stores it in the sample array, removes the index from the population index array, and resizes the population index array. Finally, it returns the sample array.

gistlibby LogSnag