我的大脑被冻结了,只是想不出解决这个问题的办法。
我创建了一个名为CustomSet的类,它包含一个字符串列表。保存对CustomSet的引用的类将其存储为列表。
public class CustomSet : IEnumerable<string>
{
public string Name { get; set; }
internal IList<string> elements;
public CustomSet(string name)
{
this.Name = name;
this.elements = new List<string>();
}
public IEnumerable<string> Elements
{
get
{
return elements;
}
}
public IEnumerator<string> GetEnumerator()
{
return elements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}因此,我想要做的是迭代这个定制集列表,输出一个2d字符串数组,其中列是customSet(s)的数目,行是customSet元素的乘法。
例如,如果列表中有3个自定义集:第一个有三个元素,第二个有两个元素,第三个有三个元素。我希望输出3列和18行(3*2*3)。以下代码是对该解决方案的尝试:
CustomSet motion = new CustomSet("Motion");
motion.Elements.Add("low");
motion.Elements.Add("medium");
motion.Elements.Add("high");
CustomSet speed = new CustomSet("Speed");
speed.Elements.Add("slow");
speed.Elements.Add("Fast");
CustomSet mass = new CustomSet("Mass");
mass.Elements.Add("light");
mass.Elements.Add("medium");
mass.Elements.Add("heavy");
List<CustomSet> aSet = new List<CustomSet>();
aSet.Add(motion);
aSet.Add(speed);
aSet.Add(mass);
//problem code
int rows = 1;
for(int i = 0; i < aSet.Count; i++)
{
rows *= aSet[i].Elements.Count;
}
string[,] array = new String[aSet.Count, rows];
int modulus;
for (int i = 0; i < aSet.Count; i++)
{
for (int j = 0; j < rows; j++)
{
modulus = j % aSet[i].Elements.Count;
array[i, j] = aSet[i].Elements[modulus];
}
}
for (int j = 0; j < rows; j++)
{
for (int i = 0; i < aSet.Count; i++)
{
Console.Write(array[i, j] + " / ");
}
Console.WriteLine();
}
//end
Console.ReadLine();但是,代码没有输出正确的字符串数组(尽管它是关闭的)。我想提出以下几点:
低/慢/轻/低/慢/轻
低/慢/中/
低/慢/重/
低/快/轻/
低/快/中/
低/快/重/
中/慢/轻/
中/慢/中/中
中/慢/重/
中/快/轻/
中/快/中/
中型/快速/重型/
高/慢/轻/
高/慢/中/
高/慢/重/重/
高/快/轻/
高/快/中/
高/快/重/重
现在,这个问题中的变量是列表中的customSets数和每个CustomSet中的元素数。
发布于 2013-08-08 16:12:42
你可以一次得到产品:
var crossJoin = from m in motion
from s in speed
from ms in mass
select new { Motion = m, Speed = s, Mass = ms };
foreach (var val in crossJoin)
{
Console.Write("{0} / {1} / {2}", val.Motion, val.Speed, val.Mass);
}现在,由于您不知道列表的数量,所以您需要做更多的工作。Eric在这篇文章中介绍了这一点,您可以使用在那里定义的CertesianProduct函数,其方式如下:
var cProduct = SomeContainerClass.CartesianProduct(aSet.Select(m => m.Elements));
var stringsToOutput = cProduct.Select(l => string.Join(" / ", l));发布于 2013-08-09 09:38:31
这种递归方法显示了所需的结果,并列出了n个CustomSet对象:
void OutputSets(List<CustomSet> aSet, int setIndex, string hirarchyString)
{
string ouputString = hirarchyString;
int nextIndex = setIndex + 1;
foreach (string element in aSet[setIndex].Elements)
{
if (nextIndex < aSet.Count)
{
OutputSets(aSet, nextIndex, hirarchyString + element + " / ");
}
else
{
Console.WriteLine(ouputString + element + " / ");
}
}
}用:
OutputSets(aSet, 0, "");https://stackoverflow.com/questions/18130773
复制相似问题