权重随机数

权重随机数

  • 需求场景
  • 应用代码

需求场景

Unity和C#中都提供的随机数的方法,但实际工作中我们常常需要对不同类型的情况有不同随机概率,这时候就需对随机数做权重处理。

应用代码

为此我抽离了一个随机数权重的静态类

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// 
/// 权重随机数
/// 
public static class WeightRandom
{
    /// 
    /// 数的区间
    /// 
    private struct Section
    {
        public float minValue;
        public float maxValue;
    }
    /// 
    /// 区间字典
    /// 
    private static Dictionary<int, Section> valueSectionDic = new Dictionary<int, Section>();

    /// 
    /// 初始化随机权重
    /// 
    public static void Init(float[] weightArray)
    {
        float startValue = 0;
        valueSectionDic.Clear();
        for (int i = 0; i < weightArray.Length; i++)
        {
            Section section = new Section();
            section.minValue = startValue;
            section.maxValue = startValue + weightArray[i];

            valueSectionDic.Add(i, section);
            startValue = section.maxValue;
        }
    }
   
    /// 
    /// 获取随机类型
    /// 
    /// 
    /// 
    public static int GetRandomType(float randmomValue)
    {
        for (int i = 0; i < valueSectionDic.Count; i++)
        {
            if (randmomValue < valueSectionDic[i].maxValue)
            {
                Debug.Log("weightType: " + i);
                return i;
            }
        }
        Debug.Log("weightType: -1");
        return -1;
    }
    
    /// 
    /// 权重水机获取
    /// 
    /// 权重数组(总和为1)
    public static int GetWeigtRandom(float[] weightArray)
    {
        Init(weightArray);
        return GetRandomType(Random.Range(0, 1.0f));
    }
}

应用代码如下,传入总和为1的随机数权重数组,即可返回对应权重的索引值

public class RandomTest : MonoBehaviour
{
    void Update()
    {
        int type = WeightRandom.GetWeigtRandom(new float[3] {0.3f, 0.1f, 0.6f });
        Debug.Log(type);
    }
}

你可能感兴趣的:(Unity3D,C#,unity3d,c#)