Random r = new Random();
private int setChosenServerByPercentage(float[] durationTime)
{
int chosenServer = -1;
float[] percentage = new float[durationTime.Length];
// set percentage
//calculate total:
float total = 0;
for (int i = 0; i < durationTime.Length; i++)
{
total += durationTime[i];
}
for (int i = 0; i < percentage.Length; i++)
{
// % of being chosen.
percentage[i] = (1f - durationTime[i] / total);
}
// likely choose one who has higher percentage
// build up the distribution percentage
float[] distr = new float[percentage.Length];
for (int i = 0; i < distr.Length; i++)
{
float tmp = percentage[i];
for (int j = 0; j < percentage.Length - 1; j++)
{
tmp *= percentage[i];
}
distr[i] = tmp;
}
// random
double rn;
while (chosenServer != -1)
{
rn = r.NextDouble();
for (int i = 0; i < distr.Length; i++)
{
if (rn < distr[i])
{
chosenServer = i;
break;
}
rn -= distr[i];
}
}
return chosenServer;
}
Random by Percentage
最新推荐文章于 2024-04-23 21:53:59 发布