• 欢迎光临~

# C# 蓄水池抽样

``````if (i < spotQuantity)
{
titleIndexList.Add(i);
eigenValueList.Add(tempEigenValue);
}
else
{
double minEigenValue = eigenValueList.Min();
int minIndex = eigenValueList.IndexOf(minEigenValue);

if (tempEigenValue > minEigenValue)
{
eigenValueList[minIndex] = tempEigenValue;
titleIndexList[minIndex] = i;
}
}

``````

``````        public static void WeightedSampling(List<article> articleList, int grade)
{
//根据传入的grade 计算一个抽样数量。
double sampleFactor = (double)Math.Pow((double)1 / (1 + grade), Math.E);
var spotQuantity = (int)Math.Ceiling(articleList.Count() * sampleFactor);
//如果规则抽的数量已经超过随机抽取数则不再抽取
var spotedCount = articleList.Where(t => t.isspot == 1).Count();
if (spotedCount >= spotQuantity)
return;
//如果数量不足则补齐
spotQuantity -= spotedCount;
var spotTitleList = articleList.Where(t => t.isspot != 1).ToList();
//实例化池子和数据权重List
List<int> titleIndexList = new List<int>();
List<double> eigenValueList = new List<double>();

if (spotArticle.Count() <= spotQuantity)
{
for (int i = 0; i < spotArticle.Count(); i++)
{
spotArticle[i].isspot = 1;
}
}
else
{
var random = new Random();
for (int i = 0; i < spotTitleList.Count; i++)
{
double tempWeight = spotTitleList[i].eigenvalue;
double tempEigenValue = Math.Pow(random.NextDouble(), 1 / tempWeight);

if (i < spotQuantity)
{
titleIndexList.Add(i);
eigenValueList.Add(tempEigenValue);
}
else
{
double minEigenValue = eigenValueList.Min();
int minIndex = eigenValueList.IndexOf(minEigenValue);

if (tempEigenValue > minEigenValue)
{
eigenValueList[minIndex] = tempEigenValue;
titleIndexList[minIndex] = i;
}
}
}
//将抽取出来的对象isspot 抽取标志设置为1
foreach (var index in titleIndexList)
{
spotTitleList[index].isspot = 1;
}
}
}
``````