问题描述
我有一个类似这样的算法:
<上一页>对于 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 循环算法 - 动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!