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);

 

vue商品规格属性(sku)组合算法_分分钟学会前端sku算法(商品多规格选择)

 https://blog.csdn.net/weixin_39875031/article/details/111284152

 

posted on 2022-02-11 13:32  asp恒心  阅读(484)  评论(0编辑  收藏  举报