迪卡尔积C#

来源:互联网 发布:手机淘宝5.8.0安卓版 编辑:程序博客网 时间:2024/04/28 20:51
     /// <summary>
        /// 迪卡尔积
        /// 
        /// (1)将每个维度的集合的元素视为List<string>,多个集合构成List<List<string>> dimvalue作为输入
        ///(2)将多维笛卡尔乘积的结果放到List<string> result之中作为输出
        ///(3)int layer, string curstring只是两个中间过程的参数携带变量
        /// (4)程序采用递归调用,起始调用示例如下:
        /// List<string> result = new List<string>();
        /// Descartes.run(dimvalue, result, 0, "");
        /// 即可获得多维笛卡尔乘积的结果。
        /// </summary>
        /// <param name="dimvalue"></param>
        /// <param name="result"></param>
        /// <param name="layer"></param>
        /// <param name="curstring"></param>
        /// 
        /// 
        /// 
        public static void Descartes(List<List<string>> dimvalue, List<string> result, int layer, string curstring)
        {
            if (layer < dimvalue.Count - 1)
            {
                if (dimvalue[layer].Count == 0)
                    Descartes(dimvalue, result, layer + 1, curstring);
                else
                {
                    for (int i = 0; i < dimvalue[layer].Count; i++)
                    {
                        StringBuilder s1 = new StringBuilder();
                        s1.Append(curstring);
                        s1.Append("," + dimvalue[layer][i]);
                        Descartes(dimvalue, result, layer + 1, s1.ToString());
                    }
                }
            }
            else if (layer == dimvalue.Count - 1)
            {
                if (dimvalue[layer].Count == 0) result.Add(curstring);
                else
                {
                    for (int i = 0; i < dimvalue[layer].Count; i++)
                    {


                        result.Add((curstring + "," + dimvalue[layer][i]).Trim(','));
                    }
                }
            }
        }
0 0
原创粉丝点击