使嵌套循环算法 - 动态 [英] Make nested for loop algorithm - dynamic
问题描述
我有一个算法是这样的:
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
我怎么能写这样反复,使之成为动态的,这样我不限制自己的for循环(I,J,K,L,M)(固定号码即我能做的(i)或( I,J)或(I,J,K)或(I,J,K,L)等...)?
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...)?
(我严格地寻求答案的动态,迭代的解决方案。如果你不明白这一点,请继续阅读,首先是previous句话。)
(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.
}
这篇关于使嵌套循环算法 - 动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!