笛卡尔积算法,商品 规格属性组合sku


  public static class UtilCombine
    {
        /// <summary>
        /// 笛卡尔乘积算法
        /// </summary>
        public static List<List<T>> CartesianProduct<T>(this List<List<T>> lstSplit)
        {
            int count = 1;
            lstSplit.ForEach(item => count *= item.Count);
            //count = lstSplit.Aggregate(1, (result, next) => result * next.Count);

            var lstResult = new List<List<T>>();

            for (int i = 0; i < count; ++i)
            {
                var lstTemp = new List<T>();
                int j = 1;
                lstSplit.ForEach(item =>
                {
                    j *= item.Count;
                    lstTemp.Add(item[(i / (count / j)) % item.Count]);
                });
                lstResult.Add(lstTemp);
            }
            return lstResult;
        }
    }

  

 // var lstSource = new List<List<string>>
           // {
           //     new List<string>() { "A","B","C"},
           //     new List<string>() { "D","E","F"},
           //     new List<string>() { "G","H","I"},
           // };
             
           // var sw = new Stopwatch();
           // sw.Start();
           // var lstResult = lstSource.CartesianProduct();

           // HashSet<string> hs = new HashSet<string> ();

           //int index=1;
           // foreach (var item1 in lstResult)
           // {
           //     string snn=item1[0]+item1[1]+item1[2];
           //     hs.Add(snn);

           //   Console.WriteLine(snn +"=="+index);
           //     index++;
           // }
            var lstSectorDef = new List<Sector>
            {
                new Sector{ name="颜色",  value=new List<string>(){"红色","黄色","绿色"}},
                new Sector{ name="尺码",  value=new List<string>(){"L","M","S"}},
                new Sector{ name="材质",  value=new List<string>(){"皮质","棉布"}},
                //.....数量不定
            };
            //第一步,去除各个规格的值,加入list
            var lstSource = new List<List<string>>();
            foreach (var item in lstSectorDef)
            {
                lstSource.Add(item.value);
            }

            var sw = new Stopwatch();
            sw.Start();
            //调用算法,计算出组合的种类和总数量,生成多少个sku,每一种sku的规格值
            var lstResult = lstSource.CartesianProduct();

            HashSet<string> hs = new HashSet<string>();

            int index = 1;
            foreach (var item1 in lstResult)
            {
                string snn = item1[0] +"-----"+ item1[1] +"-----"+ item1[2];
                hs.Add(snn);

                Console.WriteLine(snn + "==" + index);
                index++;
            }

           
            Console.WriteLine(hs.Count);
            Console.WriteLine(sw.Elapsed);
View Code

非原创,网上找的各位大神的,只为方便以后查阅记录,不喜勿喷


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM