首页 > 编程语言 > 详细

List洗牌和权重选取算法

时间:2019-03-23 12:15:44      阅读:238      评论:0      收藏:0      [点我收藏+]
using System;
using System.Collections.Generic;
using Random = UnityEngine.Random;

public static class IListExtension
{
    // 洗牌
    public static void Shuffle<T>(this IList<T> list)
    {
        for (var i = list.Count - 1; i >= 0; --i)
        {
            var index = Random.Range(0, list.Count);
            var temp  = list[index];
            list[index] = list[i];
            list[i]     = temp;
        }
    }

    // 按权重选取
    public static T SelectByWeight<T>(this IList<Tuple<int, T>> list)
    {
        var allWeight = 0;
        foreach (var (weight, _) in list)
            allWeight += weight;

        if (allWeight == 0) return default;

        var value = Random.Range(0, allWeight);
        foreach (var (weight, item) in list)
        {
            if (value < weight)
                return item;

            value -= weight;
        }

        return default;
    }
}

List洗牌和权重选取算法

原文:https://www.cnblogs.com/Fallever/p/10583242.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!