zoukankan      html  css  js  c++  java
  • List洗牌和权重选取算法

    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;
        }
       
        // 集合的子集
         public List<List<T>> Subsets<T>(this IList<T> set)
        {
            int n = set.Count, pn = 1 << n;
            List<List<T>> result  = new List<List<T>>();
            for (int pm = 0; pm < pn; pm++)
            {
                List<T> temp = new List<T>();
                for (int k = 0; k < n; k++)
                {
                    if (((1 << k) & pm) != 0)
                        temp.Add(set[k]);
                }
    
                result.Add(temp);
            }
    
            return result;
        }
        
    }
    
  • 相关阅读:
    牛客题霸NC119题解
    牛客题霸NC105题解
    牛客题霸NC93题解
    牛客题霸NC88题解
    牛客题霸NC68题解
    牛客题霸NC45题解
    牛客题霸NC33题解
    牛客题霸NC15题解
    牛客题霸NC04题解
    牛客题霸反转链表题解
  • 原文地址:https://www.cnblogs.com/Fallever/p/10583242.html
Copyright © 2011-2022 走看看