按权重随机

    以下代码为c#语言,变为其他语言也很容易。

    说明:
    1.该算法复杂度为线性,且无需对权重排序。是我想到的最高效的了。

    private static List<object> WeightKey_ = new List<object>();
    private static List<float> WeightValueFloat_ = new List<float>();
    private static List<int> WeightValueInt_ = new List<int>();

    //传入的是字典,效率不大高。
    public static object RandomObjectByWeight( Dictionary<object, float> weightInfo ) {
        WeightKey_.Clear();
        WeightValueFloat_.Clear();
        float sum = 0;
        foreach( var item in weightInfo ) {
            WeightKey_.Add( item.Key );
            WeightValueFloat_.Add( item.Value );
            sum += item.Value;
        }
        return RandomObjectByWeight( WeightKey_, WeightValueFloat_, sum );
    }

    //传入的是字典,效率不大高。
    public static object RandomObjectByWeight( Dictionary<object, int> weightInfo ) {
        WeightKey_.Clear();
        WeightValueInt_.Clear();
        int sum = 0;
        foreach( var item in weightInfo ) {
            WeightKey_.Add( item.Key );
            WeightValueInt_.Add( item.Value );
            sum += item.Value;
        }
        return RandomObjectByWeight( WeightKey_, WeightValueInt_, sum );
    }

    **//核心代码(我在项目中的做法是把sum提前存在values的最后一个值)
    public static object RandomObjectByWeight( List<object> keys, List<float> values, float sum ) {
        var r = UnityEngine.Random.Range( 0, sum );//浮点数随机为左右闭合,包含sum
        float temp = 0;
        for( int i = 0; i < values.Count; i++ ) {
            temp += values[i];
            if( r <= temp ) {
               return keys[i];
            }
        }
        return null;
    }

    public static object RandomObjectByWeight( List<object> keys, List<int> values, int sum ) {
        var r = UnityEngine.Random.Range( 0, sum )+1;//整数随机为左闭右开,不包含sum。由于0为0概率,所以加1。
        var temp = 0;
        for( int i = 0; i < values.Count; i++ ) {
            temp += values[i];
            if( r <= temp ) {
                return keys[i];
            }
        }
        return null;
    }**

按权重随机_第1张图片

效率棒棒哒^^

你可能感兴趣的:(【Unity3D】)