可调控近似概率
可调控稳定概率
using System.Collections.Generic;
using UnityEngine;
public class RandRate : MonoBehaviour
{
void Start()
{
for (int i = 0; i < 100; i++)
{
//int value = GetRandomRate(new float[5] { 0.2f, 0.3f, 0.4f, 0.05f, 0.05f });
int value = GetRateNoRandom();
Debug.Log(value);
}
}
// 约等于概率
int GetRandomRate(float[] probs)
{
float total = 0;
foreach (float elem in probs)
{
total += elem;
}
float randomPoint = Random.value * total;
for (int i = 0; i < probs.Length; i++)
{
if (randomPoint < probs[i])
{
return i;
}
else
{
randomPoint -= probs[i];
}
}
return probs.Length - 1;
}
// 数组值加起来不一定等于100,但是一般规范100 就行,要求整数
int[] NoRandomArr;
// 先初始化出来存储起来
List RandomList ;
void InitRandomListValue()
{
NoRandomArr = new int[5] {20, 30, 40, 5, 5 };
RandomList = new List();
for (int i = 0; i < NoRandomArr.Length; i++)
{
for (int j = 0; j < NoRandomArr[i]; j++)
{
RandomList.Add(i);
}
}
}
// 稳定概率 例如设置了0的概率是10 ,那么100次一定有10次,不多不少
int GetRateNoRandom()
{
if (RandomList == null ||RandomList.Count == 0) InitRandomListValue();
int listIndex = Random.Range(0, RandomList.Count - 1);
int listValue = RandomList[listIndex];
RandomList.RemoveAt(listIndex);
return listValue;
}
}



