Make nested for loop algorithm - dynamic(使嵌套 for 循环算法 - 动态)
问题描述
我有一个类似这样的算法:
<上一页>对于 m = 1 到 2初始化(工作项(m))对于 l = 1 到 2初始化(工作项(l))对于 k = 1 到 2初始化(工作项(k))对于 j = 1 到 2初始化(工作项(j))对于 i = 1 到 2初始化(work_item(i))doSomething(work_item(i))下一个做某事(工作项目(j))下一个做某事(工作项目(k))下一个做某事(工作项目(l))下一个doSomething(work_item(m))下一个如何迭代地编写它,使其动态化,这样我就不会将自己限制在固定数量的 for 循环 (i, j, k, l, m) 中(即我可以执行 (i) 或 (i, j) or (i, j, k) or (i, j, k, l) etc...)?
(我严格要求动态迭代解决方案的答案.如果您不明白这一点,请继续阅读,从上一句开始.)
完全按照使用递归的方式编写算法,但使用显式堆栈对象而不是递归.即:
var stack = new Stack();stack.Push(InitialThingy);而(堆栈.计数!= 0){var currentItem = stack.Pop();//对当前项目执行操作并在我们进行时将内容添加到堆栈.}I have an algorithm that goes something like this:
for m = 1 to 2
initialize(work_item(m))
for l = 1 to 2
initialize(work_item(l))
for k = 1 to 2
initialize(work_item(k))
for j = 1 to 2
initialize(work_item(j))
for i = 1 to 2
initialize(work_item(i))
doSomething(work_item(i))
next
doSomething(work_item(j))
next
doSomething(work_item(k))
next
doSomething(work_item(l))
next
doSomething(work_item(m))
next
How can I write this iteratively, making it dynamic, such that I don't limit myself to a fixed number of for loops (i, j, k, l, m) (i.e. I can do (i) or (i, j) or (i, j, k) or (i, j, k, l) etc...)?
(I am strictly seeking answers with dynamic, iterative solutions. If you do not understand this, please continue reading, starting with the previous sentence.)
Write your algorithm exactly as you would using recursion, but use an explicit stack object instead of recursion. I.e.:
var stack = new Stack();
stack.Push(InitialThingy);
while(stack.Count != 0)
{
var currentItem = stack.Pop();
//Do things to current item and add things to stack as we go.
}
这篇关于使嵌套 for 循环算法 - 动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使嵌套 for 循环算法 - 动态
基础教程推荐
- C# 9 新特性——record的相关总结 2023-04-03
- 获取C#保存对话框的文件路径 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
