ghx88

笛卡尔乘积算法的体现

一个商品有多项属性,多项属性的组合就产生不同的商品型号如:
衣服:
    颜色:红、绿
    尺寸:大、中、小

产生的系列就有:红|大、红|中、红|小、绿|大、绿|中、绿|小
如果商品的属性不至两个,则产生的系列会更多, A|B|C|D......
其实这是一个笛卡尔的乘积
绿
红|大 绿|大
红|中 绿|中
红|小 绿|小

如果再多一个属性(衣料): 绵、布、锦 ,也可以与上面的结果相乘,得

红|大 红|中 红|小 绿|大 绿|中 绿|小
红|大|绵 红|中|绵 红|小|绵 绿|大|绵 绿|中|绵 绿|小|绵
红|大|布 红|中|布 红|小|布 绿|大|布 绿|中|布 绿|小|布
红|大|锦 红|中|锦 红|小|锦 绿|大|锦 绿|中|锦 绿|小|锦

这样就算有再多的属性也可以随机生成结果,以下的实现的代码:
        /// <summary>
        
/// 获取商品属性组合后的列表
        
/// </summary>
        
/// <param name="attrList">属性列表数组,数组内的成员以‘|’分隔</param>
        
/// <returns>返回属性组合后的列表</returns>

        private static IList<string> GetProductModelList(IList<string> attrList)
        
{
            IList
<string> productArray = new List<string>(attrList[0].Split('|'));

            
for (int i = 1; i < attrList.Count; i++)
            
{
                productArray 
= JoinPart(productArray, attrList[i].Split('|'));
            }

            
return productArray;
        }


        
//笛卡尔乘积
        private static IList<string> JoinPart(IList<string> part1, string[] part2)
        
{
            IList
<string> result = new List<string>();
            
foreach (string str1 in part1)
            
{
                
foreach (string str2 in part2)
                
{
                    result.Add(str1 
+ "|" + str2);
                }

            }

            
return result;
        }

posted on 2007-01-29 17:04  ghx88  阅读(1305)  评论(2编辑  收藏  举报

导航