首页 / C# / c# – 使用递归的循环的未知数
c# – 使用递归的循环的未知数
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 使用递归的循环的未知数,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2186字,纯文字阅读大概需要4分钟。
内容图文
我之前做了一些研究并找到了一些很棒的文章,但我似乎无法根据我给出的问题定制任何解决方案.从完成的研究中,我认为解决这个问题的最佳方法是使用递归.我已经使用一些泛型类做了一个例子,但基本上我的问题是我在列表中有大约10个类.我可能只有这些课程中的一个,我可能有十个.对于给定的问题,我最终找到了“项目”(所有这些都继承自项目)的最佳组合.我认为这很容易,除非我必须在每次测试之前处理创建组合.
下面是一些仅使用两个类的示例代码.如果递归不是解决此问题的最佳方法,请根据需要进行更正.我如何将其转换为用于测试所需的任意数量的项目?
编辑:正如一些人已经指出我的示例代码是迭代解决方案,但它只有在我有两个项目时才有用.因此,我需要定义一个递归函数来根据运行时所需的for循环次数来解决问题.
-机会
研究:
Arbitrary number of nested-loops?
Number of nested loops at runtime
static void Main(string[] args)
{
List<Item> myItem = new List<Item>();
int numberItem1 = 0, numberItem2 = 0;
foreach (var item in myItem)
{
if (item.GetType() == typeof(Item1))
{
numberItem1++;
}
else if (item.GetType() == typeof(Item2))
{
numberItem2++;
}
}
List<Item> testingItems = new List<Item>();
//FirstItem
for (int a = 0; a < numberItem1; a++)
{
for (int b = 0; b <= a; b++)
{
testingItems.Add(new Item1 { });
}
//DoTest()
testingItems.Clear();
//Second Item
for (int c = 0; c < numberItem2; c++)
{
for (int d = 0; d <= a ; d++)
{
testingItems.Add(new Item1 { });
}
for (int e = 0; e <= c; e++)
{
testingItems.Add(new Item2 { });
}
//DoTest()
testingItems.Clear();
}
}
}
解决方法:
非递归解决方案.
IEnumerable<List<Item>> TestLists(List<Item> fullList)
{
List<Type> types = fullList.Select(i => i.GetType()).Distinct().ToList();
List<Item> testList = new List<Item> { (Item)Activator.CreateInstance(types[0]) };
yield return testList;
bool finished = false;
while (!finished)
{
bool incremented = false;
int i = 0;
while (i < types.Count && !incremented)
{
if (testList.Where(t => t.GetType() == types[i]).Count() <
fullList.Where(t => t.GetType() == types[i]).Count())
{
testList.Add((Item)Activator.CreateInstance(types[i]));
incremented = true;
}
else
{
testList = testList.Where(t => t.GetType() != types[i]).ToList();
i++;
}
}
if (incremented)
{
yield return testList;
}
else
{
finished = true;
}
}
}
用法:
foreach (var partList in TestLists(myListToTest))
{
DoTest(partList);
}
内容总结
以上是互联网集市为您收集整理的c# – 使用递归的循环的未知数全部内容,希望文章能够帮你解决c# – 使用递归的循环的未知数所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。