1. 程式人生 > >List洗牌和權重選取算法

List洗牌和權重選取算法

foreach lis default each shuf gen emp fault count

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洗牌和權重選取算法