使嵌套 for 循环算法 - 动态

Make nested for loop algorithm - dynamic(使嵌套 for 循环算法 - 动态)
本文介绍了使嵌套 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 循环算法 - 动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)