隨機(jī)相關(guān)內(nèi)容 C#實(shí)現(xiàn) Unity直接可用
洗牌代碼
//Fisher-Yates shuffle
static void Shuffle<T>(T[] array)
{
int n = array.Length;
for (int i = 0; i < n; i++)
{
int r = i + Random.Range(0, n - i);
T t = array[r];
array[r] = array[i];
array[i] = t;
}
}
帶權(quán)重隨機(jī)代碼
static public int GetRandomWeightedIndex(float[] weights)
{
// Get the total sum of all the weights.
float weightSum = 0;
for (int i = 0; i < weights.Length; ++i)
{
weightSum += weights[i];
}
// Step through all the possibilities, one by one, checking to see if each one is selected.
int index = 0;
int lastIndex = weights.Length - 1;
while (index < lastIndex)
{
// Do a probability check with a likelihood of weights[index] / weightSum.
if (Random.Range(0, weightSum) < weights[index])
{
return index;
}
// Remove the last item from the sum of total untested weights and try again.
weightSum -= weights[index++];
}
// No other item was selected, so return very last index.
return index;
}
偽隨機(jī)C系數(shù)生成代碼
static public float CfromP(float p)
{
float Cupper = p;
float Clower = 0f;
float Cmid;
float p1;
float p2 = 1f;
while (true)
{
Cmid = (Cupper + Clower) / 2f;
p1 = PfromC(Cmid);
if (Mathf.Abs(p1 - p2) <= 0f) break;
if (p1 > p)
{
Cupper = Cmid;
}
else
{
Clower = Cmid;
}
p2 = p1;
}
return Cmid;
}
private float PfromC(float C)
{
float pProcOnN = 0f;
float pProcByN = 0f;
float sumNpProcOnN = 0f;
int maxFails = Mathf.CeilToInt(1f / C);
for (int N = 1; N <= maxFails; ++N)
{
pProcOnN = Mathf.Min(1f, N * C) * (1 - pProcByN);
pProcByN += pProcOnN;
sumNpProcOnN += N * pProcOnN;
}
return (1f / sumNpProcOnN);
}
關(guān)于如何使用這上述C系數(shù)
每次觸發(fā)概率從一個(gè)值開始遞增家坎,第N次的觸發(fā)概率P(N) = C * N舞箍,比如25%的幾率,C值大概為8.5%舌胶,運(yùn)算流程如下:
第一次觸發(fā)眩暈概率為8.5%
第二次為17%,以此類推遞增
如果觸發(fā)眩暈成功彩掐,則概率重新從8.5%開始遞增計(jì)算铭若。
unity學(xué)習(xí)交流群大家可以點(diǎn)擊 一起交流學(xué)習(xí)哦