using System;
public class AliasMethod
{
private int[] alias;
private double[] prob;
public AliasMethod(double[] probabilities)
{
int n = probabilities.Length;
alias = new int[n];
prob = new double[n];
// 预处理阶段
double[] normalizedProbs = Normalize(probabilities);
SmallLarge(normalizedProbs);
}
private double[] Normalize(double[] probabilities)
{
double sum = 0;
foreach (double p in probabilities)
sum += p;
double[] normalizedProbs = new double[probabilities.Length];
for (int i = 0; i < probabilities.Length; i++)
normalizedProbs[i] = probabilities[i] / sum;
return normalizedProbs;
}
private void SmallLarge(double[] normalizedProbs)
{
int n = normalizedProbs.Length;
double[] large = new double[n];
double[] small = new double[n];
int nl = 0, ns = 0;
for (int i = 0; i < n; i++)
{
if (normalizedProbs[i] < 1)
small[ns++] = normalizedProbs[i];
else
large[nl++] = normalizedProbs[i];
}
while (ns > 0 && nl > 0)
{
double l = large[--nl];
double g = 1;
while (g > l)
g -= small[--ns];
large[nl] = l - g;
if (ns > 0)
small[ns++] = g;
}
double left = 1;
for (int i = 0; i < ns; i++)
left -= small[i];
int cur = 0;
for (int i = 0; i < ns; i++)
{
prob[cur] = small[i] / left;
alias[cur++] = n - ns + i;
}
for (int i = 0; i < nl; i++)
{
prob[cur] = large[i] / large[nl];
alias[cur++] = cur;
}
}
public int Next(Random rand)
{
int n = alias.Length;
int i = rand.Next(n);
double p = rand.NextDouble();
return p < prob[i] ? i : alias[i];
}
}
“在unity中编写C#脚本中我遇到了以下场景:存在n个选项,现在要从这n个选项中随机选出一个,且他们各自被选中的概率被设定为已知的p0、p1、p2...pn(为了便于使用,这些概….” Conversation with claude-3-sonnet-20240229, from the LMArena Human Preference 100K dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m8507bq8rx4y79pp61kjetwv