将数组随机排序
// 数组打乱排序
private T[] ShuffleArray(T[] currentArray)
{
// 从数组的最后一个序号开始,依次往前设置各序号对应的值
int maxIndex = currentArray.Length - 1;
while (maxIndex > 0)
{
// 随机选得一个序号(已设置过值的序号不再参与抽取)
int curIndex = Random.Range(0, maxIndex);
// 当前选得的随机值
T temp = currentArray[curIndex];
// 将要设置值的序号的原值暂存起来
currentArray[curIndex] = currentArray[maxIndex];
// 设置当前目标序号的值为随机选得的值
currentArray[maxIndex] = temp;
maxIndex--;
}
return currentArray;
}
根据权重抽取值
// 根据权重获取值
// 字典的键为可选值,值为权重
private static T GetValueByWeights(Dictionary weightsDict)
{
T targetValue = weightsDict.Keys.ToArray()[0];
// 当前的随机值
float currentRandomValue = Random.Range(0f, 1f);
int totalWeight = 0;
// 算出权重的总值作为分母
foreach (var value in weightsDict.Values)
totalWeight += value;
float currentProbability = 0f;
// 将权重转为概率进行计算
foreach (var k in weightsDict.Keys)
{
currentProbability += ((float)weightsDict[k] / totalWeight);
if (currentProbability >= currentRandomValue)
{
targetValue = k;
break;
}
}
return targetValue;
}