欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中实现任意List的全组合算法代码

程序员文章站 2023-12-21 15:23:46
复制代码 代码如下:using system;using system.collections.generic;using system.linq;using system...

复制代码 代码如下:

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<persontype>();
            var lstcomb = fullcombination(lstsource);
            var lstresult = new list<persontype>();
            lstcomb.foreach(item =>
            {
                lstresult.add(item.aggregate((result, source) => result | source));
            });
        }

        public static list<t> getenumlist<t>()
        {
            var lst = new list<t>();
            foreach (t item in enum.getvalues(typeof(t)))
            {
                lst.add(item);
            }
            return lst;
        }

        //全组合算法
        public static list<list<t>> fullcombination<t>(list<t> lstsource)
        {
            var n = lstsource.count;
            var max = 1 << n;
            var lstresult = new list<list<t>>();
            for (var i = 0; i < max; i++)
            {
                var lsttemp = new list<t>();
                for (var j = 0; j < n; j++)
                {
                    if ((i >> j & 1) > 0)
                    {
                        lsttemp.add(lstsource[j]);
                    }
                }
                lstresult.add(lsttemp);
            }
            lstresult.removeat(0);
            return lstresult;
        }

    }
}

上一篇:

下一篇: