-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSelectionSampling.cs
More file actions
37 lines (28 loc) · 1.08 KB
/
SelectionSampling.cs
File metadata and controls
37 lines (28 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
namespace AlgorithmsAndDataStructures.Algorithms.Sampling;
public class SelectionSampling
{
#pragma warning disable CA1822 // Mark members as static
public T[] GetRandomSample<T>(T[] population, int sampleSize)
#pragma warning restore CA1822 // Mark members as static
{
if (population is null) return Array.Empty<T>();
if (population.Length < sampleSize)
throw new ArgumentException($"{nameof(sampleSize)} must be smaller then population size.");
var result = new T[sampleSize];
var selectedCounter = 0;
var populationPointer = 0;
var random = new Random();
while (selectedCounter < sampleSize)
{
var randomNumber = random.NextDouble();
if (randomNumber * (population.Length - populationPointer) < sampleSize - selectedCounter)
{
result[selectedCounter] = population[populationPointer];
selectedCounter++;
}
populationPointer++;
}
return result;
}
}