[asp.net core]asp.net C# 实现任意List的全组合算法代码

更新时间:2018-07-28    来源:php常用代码    手机版     字体:

【www.bbyears.com--php常用代码】

 代码如下


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 算法
{
    class 全组合算法
    {
        [Flags]
        public enum PersonType
        {
            Audit = 1,
            Child = 2,
            Senior = 4
        }

        public static void Run(string[] args)
        {
            var lstSource = GetEnumList();
            var lstComb = FullCombination(lstSource);
            var lstResult = new List();
            lstComb.ForEach(item =>
            {
                lstResult.Add(item.Aggregate((result, source) => result | source));
            });
        }

        public static List GetEnumList()
        {
            var lst = new List();
            foreach (T item in Enum.GetValues(typeof(T)))
            {
                lst.Add(item);
            }
            return lst;
        }

        //全组合算法
        public static List> FullCombination(List lstSource)
        {
            var n = lstSource.Count;
            var max = 1 << n;
            var lstResult = new List>();
            for (var i = 0; i < max; i++)
            {
                var lstTemp = new List();
                for (var j = 0; j < n; j++)
                {
                    if ((i >> j & 1) > 0)
                    {
                        lstTemp.Add(lstSource[j]);
                    }
                }
                lstResult.Add(lstTemp);
            }
            lstResult.RemoveAt(0);
            return lstResult;
        }

    }
}

本文来源:http://www.bbyears.com/jiaocheng/43176.html