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.cs787 chars23 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