CSDN广告是越来越多了,所有博客笔记不再更新,新网址 DotNet笔记
1:核心代码,抄的百度百科,如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class Descartes
{
/// <summary>
/// 笛卡尔积
/// </summary>
/// <param name="dimvalue">将每个维度的集合的元素视为List<string>,多个集合构成List<List<string>> dimvalue作为输入</param>
/// <param name="result">将多维笛卡尔乘积的结果放到List<string> result之中作为输出</param>
/// <param name="layer">int layer 只是两个中间过程的参数携带变量</param>
/// <param name="curstring"> string curstring只是两个中间过程的参数携带变量,传递""就行</param>
public static void run(List<List<string>> dimvalue, List<string> result, int layer=0, string curstring="")
{
if (layer < dimvalue.Count - 1)
{
if (dimvalue[layer].Count == 0)
run(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]);
run(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]);
}
}
}
}
}
2:调用方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DKR
{
class Program
{
static void Main(string[] args)
{
//笛卡尔积:设A,B为集合,用A中元素为第一元素,B中元素为第二元素构成有序对,所有这样的有序对组成的集合叫做A与B的笛卡尔积,记作AxB.
//---------------以下方法用来测试------------------------
//建立数据源 集合l1
List<String> l1 = new List<string>();
for (int i = 1; i < 5; i++)
{
l1.Add("a"+i.ToString()+" ");
}
//建立数据源 集合l2
List<String> l2 = new List<string>();
for (int i =1; i < 4; i++)
{
l2.Add("b" + i.ToString() + " ");
}
//建立数据源 集合l3
List<String> l3 = new List<string>();
for (int i = 1; i < 3; i++)
{
l3.Add("c" + i.ToString() + " ");
}
//把需要进行笛卡尔积计算的集合放入到 List<List<string>>对象中
List<List<string>> dimvalue = new List<List<string>>();
dimvalue.Add(l1);
dimvalue.Add(l2);
dimvalue.Add(l3);
//建立结果容器 List<string> result
List<string> result = new List<string>();
//传递给计算方法中计算
Descartes.run(dimvalue, result);
//遍历查询结果
foreach (string s in result)
{
Console.WriteLine(s);
}
Console.Read();
}
}
}
3:运行结果(部分截图)